问题保存 strokeStyle

Issue saving strokeStyle

我很难理解为什么 canvas 上的样式堆栈在使用 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();

所以我的输出应该是两条蓝线和一条红线,但出于某种奇怪的原因,我得到了两条紫线和一条红线。我不明白为什么会这样。

因为它每次更改时都会为​​整个路径设置 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 />