<canvas></canvas>只是一个绘制图形的容器,除了id、class、style等属性外,还有height和width属性。在<canvas>>元素上绘图主要有三步:
1.获取<canvas>元素对应的DOM对象,这是一个Canvas对象;
2.调用Canvas对象的getContext()方法,得到一个CanvasRenderingContext2D对象;
3.调用CanvasRenderingContext2D对象进行绘图。
绘制矩形rect()、fillRect()和strokeRect()
•context.rect( x , y , width , height ):只定义矩形的路径;
•context.fillRect( x , y , width , height ):直接绘制出填充的矩形;
•context.strokeRect( x , y , width , height ):直接绘制出矩形边框;
- <script type="text/javascript"> var canvas = document.getElementById("canvas");
- var context = canvas.getContext("2d");
- //使用rect方法 context.rect(10,10,190,190);
- context.lineWidth = 2; context.fillStyle = "#3EE4CB";
- context.strokeStyle = "#F5270B"; context.fill();
- context.stroke();
- //使用fillRect方法 context.fillStyle = "#1424DE";
- context.fillRect(210,10,190,190);
- //使用strokeRect方法 context.strokeStyle = "#F5270B";
- context.strokeRect(410,10,190,190);
- //同时使用strokeRect方法和fillRect方法 context.fillStyle = "#1424DE";
- context.strokeStyle = "#F5270B"; context.strokeRect(610,10,190,190);
- context.fillRect(610,10,190,190); </script>

这里需要说明两点:第一点就是stroke()和fill()绘制的前后顺序,如果fill()后面绘制,那么当stroke边框较大时,会明显的把stroke()绘制出的边框遮住一半;第二点:设置fillStyle或strokeStyle属性时,可以通过“rgba(255,0,0,0.2)”的设置方式来设置,这个设置的最后一个参数是透明度。









