Friday, May 17, 2024
98
rated 0 times [  99] [ 1]  / answers: 1 / hits: 19649  / 12 Years ago, fri, august 10, 2012, 12:00:00

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.


More From » html5-canvas

 Answers
11

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/


[#83723] Wednesday, August 8, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
trentb

Total Points: 261
Total Questions: 101
Total Answers: 90

Location: French Southern and Antarctic Lands
Member since Fri, Jan 6, 2023
1 Year ago
;