为什么我不能在HTML5画布中画出两行不同的颜色?

时间:2012-08-10 05:10:26

标签: html5-canvas

我正在尝试使用HTML5画布在绿线左侧绘制一条红线。这是我的javascript:

var canvas = document.createElement('canvas');
canvas.height = 150;
canvas.width = 150;
var canvasContext = canvas.getContext('2d');
canvasContext.beginPath();

// Draw the red line.
canvasContext.strokeStyle = '#f00';
canvasContext.moveTo(10, 0);
canvasContext.lineTo(10, 100);
canvasContext.stroke();

// Draw the green line.
canvasContext.moveTo(50, 0);
canvasContext.strokeStyle = '#0f0';
canvasContext.lineTo(50, 100);
canvasContext.stroke();

document.body.appendChild(canvas);​

然而,在谷歌浏览器中,我在浅绿色线的左侧出现深绿色线条。为什么?我两次叫中风吧?因此,为什么我的第一次中风影响我的第二次?

Here是一个JSFiddle,它说明了我的意思。

2 个答案:

答案 0 :(得分:24)

当你开始画第二行时,你没有打电话给canvasContext.beginPath();

为了使绘图部分更加独立,我添加了空格:

var canvas = document.createElement('canvas');
canvas.height = 150;
canvas.width = 150;

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

// Draw the red line.
canvasContext.beginPath();
canvasContext.strokeStyle = '#f00';
canvasContext.moveTo(10, 0);
canvasContext.lineTo(10, 100);
canvasContext.stroke();

// Draw the green line.
canvasContext.beginPath();
canvasContext.moveTo(50, 0);
canvasContext.strokeStyle = '#0f0';
canvasContext.lineTo(50, 100);
canvasContext.stroke();

document.body.appendChild(canvas); 

演示:http://jsfiddle.net/AhdJr/2/

答案 1 :(得分:4)

非常有趣,因为我可以告诉webgl或opengl的工作方式就像一个大型状态机,你可以在其中定义一个状态,绘制,再次更新状态绘图,等等......

虽然我不确定canvas是否遵循相同的原则,即使它只是用于简单的2D渲染。

我设法让它只是开始一条新路径。

var canvas = document.createElement('canvas');
canvas.height = 150;
canvas.width = 150;
var canvasContext = canvas.getContext('2d');
canvasContext.beginPath();

// Draw the red line.

canvasContext.moveTo(10, 0);
canvasContext.lineTo(10, 100);
canvasContext.strokeStyle = '#FF0000';
canvasContext.stroke();

canvasContext.beginPath(); // begin new path
// Draw the green line.
canvasContext.moveTo(50, 0);
canvasContext.strokeStyle = '#00FF00';
canvasContext.lineTo(50, 100);
canvasContext.stroke();

document.body.appendChild(canvas);​

我对webgl的经验有限,所以如果我错了,请纠正我。