Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GWT Canvas: how to change line color

Tags:

colors

canvas

gwt

Since the canvas drawing in GWT has been all over the map, let me be explicit and say I'm using this:

import com.google.gwt.canvas.client.Canvas;

The problem is that if I draw a black line and then change to red, the first line is changed to red also.

// draw line in black
 context.moveTo(xScale(-0.5), yScale(0.0));
 context.lineTo(xScale(15.0), yScale(0.0));
 context.stroke();

 // change to red
 context.setStrokeStyle(CssColor.make(255,0,0));


 context.moveTo(xScale(0.0), yScale(20.0));
 context.lineTo(xScale(0.0), yScale(-20.0));
 context.stroke();

 // both lines appear in red

What is the correct method for changing pen color?

like image 417
SeaDrive Avatar asked Feb 19 '12 16:02

SeaDrive


1 Answers

Calling context.beginPath() before each new shape/line with different color should fix your problem.

// draw line in black
 context.beginPath();
 context.moveTo(xScale(-0.5), yScale(0.0));
 context.lineTo(xScale(15.0), yScale(0.0));
 context.stroke();

 context.beginPath();
 // change to red
 context.setStrokeStyle(CssColor.make(255,0,0));

 context.moveTo(xScale(0.0), yScale(20.0));
 context.lineTo(xScale(0.0), yScale(-20.0));
 context.stroke();

 // both lines appear in red

Basically beginPath() pushed the state

like image 107
Ümit Avatar answered Sep 19 '22 09:09

Ümit