先举个简单的例子,
var myCanvas = document.getElementById("myCanvas");
var context= myCanvas.getContext("2d");
context.beginPath();
context.moveTo(150, 50);
context.lineTo(250, 50);
context.strokeStyle = "green";
context.stroke();
context.beginPath();
context.moveTo(150, 80);
context.lineTo(250, 80);
context.strokeStyle = "yellow";
context.stroke();
context.beginPath();
context.moveTo(150, 100);
context.lineTo(250, 100);
context.strokeStyle = "blue";
context.stroke();
这个例子会从上向下依次绘制三条横线,效果如图:
假如去掉第三个beginPath()方法,会发现第三条线的颜色同时也绘制到第二条黄线上,这就发现beginPath()方法会让图形在绘制时重新找到开始点绘制而不会和之前的绘图重叠,加上他还是很必须的。