我正在努力理解为什么画布上的样式堆栈在使用strokStyle时不起作用。 到目前为止,我得到了这个。
ctx_graph.strokeStyle = "blue";
ctx_graph.moveTo(100,100);
ctx_graph.lineTo(150,150);
ctx_graph.stroke();
ctx_graph.save();
ctx_graph.moveTo(200,100);
ctx_graph.lineTo(300,300);
ctx_graph.stroke();
ctx_graph.strokeStyle = "red";
ctx_graph.moveTo(250,100);
ctx_graph.lineTo(350,350);
ctx_graph.stroke();
ctx_graph.save();
所以我的输出应该是两条蓝线和一条红线,但由于一些奇怪的原因,我得到两条紫色线和一条红线。我无法弄清楚为什么会发生这种情况。
答案 0 :(得分:0)
因为每次更改时,它都会为整个路径设置strokeColor
。因此,"blue"
和"red"
之间的项目将同时应用这两种颜色,从而获得紫色。要分隔路径,请通过调用beginPath
(这将开始一条新路径)封闭您的行,否则它只会合并strokeColor
中设置的两种颜色:
var ctx_graph = document.getElementById("canvas").getContext("2d");
ctx_graph.beginPath();
ctx_graph.strokeStyle = "blue";
ctx_graph.moveTo(100,100);
ctx_graph.lineTo(150,150);
ctx_graph.stroke();
ctx_graph.save();
ctx_graph.moveTo(200,100);
ctx_graph.lineTo(300,300);
ctx_graph.stroke();
// Calling beginPath here will close the last path, so the items above will not have both
// colors.
ctx_graph.beginPath();
ctx_graph.strokeStyle = "red";
ctx_graph.moveTo(250,100);
ctx_graph.lineTo(350,350);
ctx_graph.stroke();
ctx_graph.save();

<canvas id="canvas" width=400 height=400 />
&#13;