gpt4 book ai didi

javascript - 意想不到的颜色?

转载 作者:太空宇宙 更新时间:2023-11-04 15:28:26 25 4
gpt4 key购买 nike

所以我创建了一些小方法来更轻松地创建 Canvas 。以下是与意外结果相关的部分:

var Functions = {
createCanvas: function (width, height) {
...
return {
...
line: function (obj) {
var ctx = this.ctx;
ctx.save();
ctx.moveTo(obj.x, obj.y);
ctx.lineTo(obj.a, obj.b);
ctx.lineWidth = (obj.width || 1);
ctx.strokeStyle = (obj.color || "black");
ctx.stroke();
ctx.restore();
return this;
},
...
}
}
}

这确实有效,它确实在正确的位置画了一条线,但是当我以这种方式指定颜色时,它似乎总是使用为链中绘制的所有线指定的最后一种颜色:

Functions.createCanvas(100, 100).line({
x: 10, y: 0.5,
a: 90, b: 0.5,
color: "blue"
}).line({
x: 10, y: 2.5,
a: 90, b: 2.5,
color: "red"
});

第一行应该是蓝色的;然而,不知何故它最终变成了红色。

我真的找不到问题出在哪里,因为第一条线应该在第二条 line() 被调用之前就画好了。有什么想法吗?

这是全部内容:http://jsfiddle.net/DerekL/nzRSY/

最佳答案

确保使用 ctx.beginPath() 开始画线;

       line: function (obj) {
var ctx = this.ctx;
ctx.beginPath(); // or else the next fillstyle will overwrite
ctx.save();
ctx.moveTo(obj.x, obj.y);
ctx.lineTo(obj.a, obj.b);
ctx.lineWidth = (obj.width || 1);
ctx.strokeStyle = (obj.color || "black");
ctx.stroke();
ctx.restore();
return this;
},

关于javascript - 意想不到的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17057053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com