scrblnrd3
scrblnrd3

Reputation: 7416

Unexpected behavior of strokeStyle in canvas

I'm working on a Javascript graphing library in javascript, and I have a function that draws the grid, with each gridline having one color, and the axes having another color. The relevant code is at this jsfiddle http://jsfiddle.net/F5LPn/#run
The main method that is being called is at the bottom, as the top has to load.

var ctx=document.getElementById('canvas').getContext('2d');
ctx.line(0,0,5,5);
ctx.lineWidth=1;
ctx.setGraph(-10,10,-10,10,1,1);
ctx.drawGraph('lightgrey','black');
ctx.strokeStyle='pink';
ctx.line(0,0,5,5);

The drawGraph method uses this code

CanvasRenderingContext2D.prototype.drawGraph=function(color,axiscolor){
alert('called!');
this.strokeStyle=color;
for(var i=this.xmin;i<=this.xmax;i+=this.xscl){
    this.line(i,this.xmin,i,this.xmax);
}
for(var j=this.ymin;j<=this.ymax;j+=this.yscl){
    this.line(this.ymin,j,this.ymax,j);
}
//  this.strokeStyle=axiscolor;
this.line(0,this.xmin,0,this.xmax);
this.line(this.ymin,0,this.ymax,0);
this.strokeStyle=color;
};

As you can see, at least in my browser, even though the strokestyle is being set to green after the drawgraph is called, the whole grid is colored green. I have no clue why this is happening

Thanks

Upvotes: 0

Views: 98

Answers (2)

Dave
Dave

Reputation: 46249

Your issue is that you don't beginPath in your line function. So your grid actually gets drawn twice; once in lightgrey and once in pink, because in the line call, it still has all the data for the grid lines.

Aside from that, you shouldn't add methods to a built-in object (especially in a library)

Upvotes: 1

sixFingers
sixFingers

Reputation: 1295

Actually I'm not able to run your code - only the graph container rectangle gets drawn - but i normally do this to switch colors while drawing:

ctx.strokeStyle = "colorValue";
ctx.beginPath();
ctx.moveTo(sx, sy);
ctx.lineTo(ex, ey);
ctx.stroke();

Then again:

ctx.strokeStyle = "colorValue";
ctx.beginPath();
ctx.moveTo(sx, sy);
ctx.lineTo(ex, ey);
ctx.stroke();

Upvotes: 0

Related Questions