문제

There is a tiny sample at the URL below that draws two lines. I expect the top line to be green and the bottom to be blue. But they are both blue. Why?

http://jsfiddle.net/rj8Ab/

EDIT Adding the script below as well:

var canvas = document.getElementById('canvas');
canvas.width = 500;
canvas.height = 500;

var ctx = canvas.getContext('2d');

ctx.globalAlpha = 1;
ctx.globalCompositeOperation = "source-over";

var x1=10, y1=10, width=100, height=100;

ctx.lineWidth = "5";

//draw green line
ctx.strokeStyle = "#00FF00";
ctx.moveTo(x1 + 1, y1 + 1);
ctx.lineTo(x1 + width - 2, y1 + 1);
ctx.stroke();

//draw blue line
ctx.strokeStyle = "#0000FF";
ctx.moveTo(x1 + 1, y1 + 10);
ctx.lineTo(x1 + width - 2, y1 + 10);
ctx.stroke();
도움이 되었습니까?

해결책

You have to start a new path if you want so - .stroke doesn't do that automatically: http://jsfiddle.net/rj8Ab/2/.

//draw blue line
ctx.beginPath();

Currently the path is extended with the second line, so the new path consists of two lines. You're first stroking the top line green, and after that you're extending the path and stroking the path blue (which now consists of both lines). Obviously the green line has been "overwritten".

다른 팁

The first bar is drawn green, but it is then changed to blue color.

As seen on www.williammalone.com

//draw green line
ctx.beginPath();
ctx.moveTo(x1 + 1, y1 + 1);
ctx.lineTo(x1 + width - 2, y1 + 1);
ctx.closePath();
ctx.strokeStyle = "#00FF00";
ctx.stroke();
//draw blue line
ctx.beginPath();
ctx.moveTo(x1 + 1, y1 + 10);
ctx.lineTo(x1 + width - 2, y1 + 10);
ctx.closePath();
ctx.strokeStyle = "#0000FF";
ctx.stroke();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top