如何设置点的颜色(线到)



我想在绘制线条后更改线条在某个指针处的颜色。
我一开始将strokeStyle设置为蓝色,后来指向绿色。
但是,整行显示为绿色。有没有办法在绘制线条时更改线条的颜色?

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.strokeStyle = '#0000ff';  // set color to blue
ctx.lineWidth = 1; 
// HOWEVER IT DRAWS IN GREEN - Why ?
ctx.moveTo(20, 20);
ctx.lineTo(20, 100);
ctx.lineTo(70,100);
ctx.moveTo(50,50);
ctx.lineTo(50,51);
ctx.moveTo(53,50);
ctx.lineTo(53,51);
ctx.stroke();
// Above color should be Blue  
// Now set the color to green 
ctx.strokeStyle = '#00ff00';
ctx.moveTo(50,53);
ctx.lineTo(50,54);
ctx.moveTo(53,53);
ctx.lineTo(53,54);
ctx.stroke();
#myCanvas {
	height: 100%;
	width: 100%;
}
<p><strong>Note:</strong> Example 2  Two Lines and a dot.</p>
<canvas id="myCanvas"></canvas>

您添加ctx.beginPath();太早了。在将颜色更改为绿色后,您还需要再次添加它。

请参阅此示例:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.strokeStyle = '#0000ff';  // set color to blue
ctx.lineWidth = 1; 
//add beginPath() here:
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(20, 100);
ctx.lineTo(70,100);
ctx.moveTo(50,50);
ctx.lineTo(50,51);
ctx.moveTo(53,50);
ctx.lineTo(53,51);
ctx.stroke();
ctx.strokeStyle = '#00ff00';
//again, add beginPath() to make the new dots green:
ctx.beginPath();
ctx.moveTo(50,53);
ctx.lineTo(50,54);
ctx.moveTo(53,53);
ctx.lineTo(53,54);
ctx.stroke();
<p><strong>Note:</strong> Example 2  Two Lines and a dot.</p>
<canvas id="myCanvas"></div>

最新更新