HTML 5 Canvas样式泄漏

时间:2012-06-30 17:38:29

标签: html5-canvas stroke

下面的网址上有一个小样本,可以绘制两行。我希望顶线为绿色,底部为蓝色。但它们都是蓝色的。为什么呢?

http://jsfiddle.net/rj8Ab/

编辑也添加以下脚本:

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();

2 个答案:

答案 0 :(得分:1)

如果您愿意,您必须开始新的路径 - .stroke不会自动执行此操作:http://jsfiddle.net/rj8Ab/2/

//draw blue line
ctx.beginPath();

目前路径是扩展,第二行,所以新路径由两行组成。你是第一次抚摸绿线的顶线,然后你扩展路径并抚摸蓝色路径(现在由两条线组成)。显然绿线已被“覆盖”。

答案 1 :(得分:0)

第一个条形图为绿色,但随后会变为蓝色。

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();