我正在尝试使用 HTML5 Canvas 在绿线的左侧绘制一条红线。这是我的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两次对吧?因此,为什么我的第一次中风会影响我的第二次?
Here是一个 JSFiddle,说明了我的意思。
最佳答案
你没有调用 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/
关于html5-canvas - 为什么我不能在我的 HTML5 Canvas 中绘制两条不同颜色的线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11895807/