0

我正在使用 javascript 开发一个 Javascript 图形库,我有一个绘制网格的函数,每条网格线都有一种颜色,而轴有另一种颜色。相关代码在这个 jsfiddle http://jsfiddle.net/F5LPn/#run
被调用的主要方法在底部,因为顶部必须加载。

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);

drawGraph 方法使用此代码

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;
};

正如您所看到的,至少在我的浏览器中,即使在调用绘图图之后将笔画样式设置为绿色,整个网格也是绿色的。我不知道为什么会这样

谢谢

4

2 回答 2

1

你的问题是你不在beginPath你的line功能中。所以你的网格实际上被绘制了两次;一次是浅灰色,一次是粉红色,因为在线调用中,它仍然具有网格线的所有数据。

除此之外,您不应该将方法添加到内置对象(尤其是在库中)

于 2013-05-15T22:34:35.140 回答
0

实际上我无法运行您的代码-仅绘制图形容器矩形-但我通常这样做是为了在绘制时切换颜色:

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

再说一遍:

ctx.strokeStyle = "colorValue";
ctx.beginPath();
ctx.moveTo(sx, sy);
ctx.lineTo(ex, ey);
ctx.stroke();
于 2013-05-15T22:27:30.667 回答