22

我正在尝试使用 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);​

但是,在 Google Chrome 中,我在浅绿色线的左侧看到了一条深绿色线。为什么?我叫了stroke两次对吧?因此,为什么我的第一次中风会影响我的第二次?

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

4

2 回答 2

39

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/

于 2012-08-10T05:20:14.307 回答
5

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

虽然我不确定画布是否遵循相同的原则,即使它只是用于简单的 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 的经验有限,所以如果我弄错了,请纠正我。

于 2012-08-10T05:20:13.313 回答