gpt4 book ai didi

javascript - 所有圆圈都以相同的颜色绘制

转载 作者:行者123 更新时间:2023-12-04 10:22:54 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Drawing lines with canvas by using for loop

(2 个回答)


去年关闭。




简而言之,问题是这样的。我想在 Canvas 上用不同的颜色绘制两个圆圈。出于某种原因,它们以相同的颜色绘制,即使我放入的控制台日志在“绿色”和“蓝色”之间切换。抱歉,有些变量名称是我的母语,如果这会带来问题,请提问,我会翻译。

var bodyEl = document.querySelector("body");
var canvasEl = document.createElement("canvas");
var height = window.innerHeight;
var width = window.innerWidth;
canvasEl.height = height;
canvasEl.width = width;
bodyEl.appendChild(canvasEl);
var ctx = canvasEl.getContext("2d");
var obj = [];

class ball {
constructor(radius, farge, xPosisjon, yPosisjon) {
this.x = xPosisjon;
this.y = yPosisjon;
this.rad = radius;
this.farge = farge;
}
get areal() {
let areal = "areal: " + (Math.PI * this.rad * this.rad + "px");
return (areal);
}
tegn() {
//console.log(this.farge);
ctx.fillStyle = this.farge;
ctx.arc(this.x, this.y, this.rad, 0, 2 * Math.PI);
ctx.fill();
}
}

obj.push(new ball(20, "green", 100, 100));
obj.push(new ball(30, "blue", 500, 300));

setInterval(() => {
obj.forEach(x => {
x.tegn();
});
}, 30);

最佳答案

您需要添加一个 ctx.beginPath() .

您看到相同颜色的原因与此问题中发现的相同问题有关:Drawing lines with canvas by using for loop .如果您不使用 beginPath() ,您不断将绘制命令推送到相同的(根)路径,然后绘制越来越复杂的路径。

您必须使用 beginPath开始一个子路径。 ctx.fill()将关闭子路径。 closePath is optional .

The third, and an optional step, is to call closePath(). This method tries to close the shape by drawing a straight line from the current point to the start. If the shape has already been closed or there's only one point in the list, this function does nothing.



var bodyEl = document.querySelector("body");
var canvasEl = document.createElement("canvas");
var height = window.innerHeight;
var width = window.innerWidth;
canvasEl.height = height;
canvasEl.width = width;
bodyEl.appendChild(canvasEl);
var ctx = canvasEl.getContext("2d");
var obj = [];

class ball {
constructor(radius, farge, xPosisjon, yPosisjon) {
this.x = xPosisjon;
this.y = yPosisjon;
this.rad = radius;
this.farge = farge;
}
get areal() {
let areal = "areal: " + (Math.PI * this.rad * this.rad + "px");
return (areal);
}
tegn() {
//console.log(this.farge);
ctx.beginPath();
ctx.fillStyle = this.farge;
ctx.arc(this.x, this.y, this.rad, 0, 2 * Math.PI);
ctx.fill();
}
}

obj.push(new ball(20, "green", 100, 100));
obj.push(new ball(30, "blue", 500, 300));

setInterval(() => {
ctx.clearRect(0,0,500,500);
obj.forEach(x => {
x.tegn();
});
}, 1000);

关于javascript - 所有圆圈都以相同的颜色绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60757641/

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