先贴上网上看到的博客,侵删。
<canvas id="myCanvas" width="300" height="300" style="border:1px solid #000000;">
您的浏览器不支持 HTML5 canvas 标签。
</canvas>
<script>
var ctx = document.getElementById("myCanvas").getContext('2d');
ctx.beginPath();
ctx.moveTo(100.5,20.5);//①
ctx.lineTo(200.5,20.5);//②
ctx.strokeStyle = 'black';//默认strokeStyle='black', lineWidth=1, 此处可省略
ctx.stroke();
ctx.moveTo(100.5,40.5);//③
ctx.lineTo(200.5,40.5)//④
ctx.strokeStyle = 'red';
ctx.stroke();
</script>
- beginPath
canvas中的绘制方法(如stroke, fill),都会以“上一次beginPath”之后的所有路径为基础进行绘制。比如上述代码实际会画两条红线,而不是一条黑线,一条红线,stroke了两次,都是以第一次beginPath后的所有路径为基础画的。
-
第一次stroke:画①②,黑色
-
第二次stroke:画①②③④,红色(其中①②红色