html5画布描边两次再次绘制第一次描边

Rod*_*igo 3 html javascript canvas

我想用一种颜色画一条线,用另一种颜色画下一条线。但是当我第二次调用中风()时,第一条线又被绘制了!我怎样才能避免它?这是我的代码:

var canv = document.getElementById("canvas");
var ctx = canv.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(100,100);
ctx.strokeStyle = "#FF0000";
ctx.stroke();
ctx.moveTo(100,100);
ctx.lineTo(100,200);
ctx.strokeStyle = "#999999";
ctx.stroke();
Run Code Online (Sandbox Code Playgroud)

提前致谢!

小智 6

beginPath()只需在其中插入一个:

var canv = document.getElementById("canvas");
var ctx = canv.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(100,100);
ctx.strokeStyle = "#FF0000";
ctx.stroke();

cxt.beginPath();   // <---
ctx.moveTo(100,100);
ctx.lineTo(100,200);
ctx.strokeStyle = "#999999";
ctx.stroke();
Run Code Online (Sandbox Code Playgroud)

这将重置你的路径。描边只是描画路径上存在的东西,但不会清除它。您必须手动重置要绘制的每个新形状的路径。

优点是您可以重复使用该路径进行填充、剪辑和点测试。缺点是有时很容易忘记。