Reputation: 20895
I am trying to use HTML5 canvas to draw a red line to the left of a green line. Here is my 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);
However, in Google Chrome, I get a dark green line to the left of a light green line. Why? I called stroke twice right? Hence, why should my first stroke affect my second one?
Here is a JSFiddle that illustrates what I mean.
Upvotes: 28
Views: 21415
Reputation: 298176
You aren't calling canvasContext.beginPath();
when you start drawing your second line.
To make the drawing sections more independent, I added whitespace:
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);
Demo: http://jsfiddle.net/AhdJr/2/
Upvotes: 47
Reputation: 11130
very interesting as far as I can tell the way webgl or opengl work is like a large state machine, where you define a state, draw, update the state draw again, and so on ...
Though Im not sure if canvas follows the same principles even if its just meant for simple 2d renderings.
I managed to ge it working simply beginning a new path.
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);
I have limited experience with webgl so if Im mistaken please correct me.
Upvotes: 7