【发布时间】:2021-06-16 23:28:27
【问题描述】:
所以我一直在研究用于在画布中绘制函数的 JavaScript 库,在设置图表的函数中,我遇到了一些非常奇怪的行为。在某些地方,ctx.strokeStyle 被更改为使用不同的颜色进行绘制,但由于某种原因,每个函数都使用一种颜色进行绘制,并且仅在某一点使用过。
var chartCount = 0;
class chart {
constructor(gnx, gx, gny, gy) {
this.canvas = document.createElement("CANVAS");
document.body.appendChild(this.canvas);
this.canvas.width = 400;
this.canvas.height = 400;
this.canvas.style = "border:1px solid #000000;";
this.ctx = this.canvas.getContext("2d");
this.id = "htmlCanvasGraph#" + chartCount;
chartCount++;
this.gnx = gnx;
this.gx = gx;
this.gny = gny;
this.gy = gy;
this.ry = this.canvas.height / (this.gny + this.gy);
this.rx = this.canvas.width / (this.gnx + this.gx);
this.outline();
}
cx(x) { //convert a graph value to a canvas value
return (x + this.gnx) * this.rx;
}
cy(y) { //convert a graph value to a canvas value
return this.canvas.height - (y + this.gny) * this.ry;
}
outline() { //creates the axis and graph lines
this.drawline(0 - this.gnx, this.gx, 0, 0, 3, "#000000"); //BLACK
this.drawline(0, 0, 0 - this.gny, this.gy, 3, "#000000");
var i = 0;
while (i < this.gx) { //quadrants 1 and 4
i += 10;
this.drawline(i, i, this.gy, -1 * this.gny, 1, "#808080"); //GREY
} // FOR SOME REASON EVERY SINGLE LINE IS THAT ^ COLOR
} //ALSO IF YOU LOOK CLOSELY OR CHANGE IT TO BLACK YOU CAN SEE THE LINES SLIGHTLY FADE OUT AS MOVEING LEFT TO RIGHT, NO IDEA WHY
drawline(x1, x2, y1, y2, w, c) {
this.ctx.lineWidth = w;
this.ctx.strokeStyle = c;
this.ctx.moveTo(this.cx(x1), this.cy(y1));
this.ctx.lineTo(this.cx(x2), this.cy(y2));
this.ctx.stroke();
}
}
const graph1 = new chart(100, 100, 100, 100)
Here is the whole script on JS Fiddle
您可以看到每条线都是灰色的,尽管两条较宽的线应该是黑色的。
另一个问题是网格线是从左到右绘制的,它们由于某种原因变得越来越轻,不知道是什么原因造成的,因为每条线之间的宽度、颜色和 alpha 应该相同。
【问题讨论】:
标签: javascript html html5-canvas