context.lineWidth = 2;
context.strokeStyle = "#F5270B";
//绘制
context.stroke();
context.beginPath();
context.moveTo(100,200);//这里的moveTo换成lineTo效果是一样的
context.lineTo(600,200);
context.lineTo(600,400);
//strokeStyle的颜色有新的值,则覆盖上面设置的值
//lineWidth没有新的值,则按上面设置的值显示
context.strokeStyle = "#0D25F6";
//绘制
context.stroke();
</script>

绘制矩形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)”的设置方式来设置,这个设置的最后一个参数是透明度。
另外还有一个跟矩形绘制有关的:清除矩形区域:context.clearRect(x,y,width,height)。
接收参数分别为:清除矩形的起始位置以及矩形的宽和长。
在上面的代码中绘制图形的最后加上:
context.clearRect(100,60,600,100);可以得到以下效果:

绘制五角星
通过对五角星分析,我们可以确定各个顶点坐标的规律,这里需要注意的一点是:在canvas中,Y轴的方向是向下的。









