javascript - 所有圆圈都以相同的颜色绘制
问题描述
简而言之,问题就是这个。我想在画布上画两个不同颜色的圆圈。出于某种原因,它们以相同的颜色绘制,即使我放置的控制台日志在“绿色”和“蓝色”之间切换。抱歉,有些变量名是我的母语,如果有问题,请询问,我会翻译。
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()
.
您看到相同颜色的原因与此问题中发现的相同问题有关:使用 for loop 使用画布绘制线条。如果您不使用beginPath()
,则继续将绘制命令推送到相同的(根)路径,然后绘制越来越复杂的路径。
您必须使用beginPath
来启动子路径。 ctx.fill()
将关闭子路径。closePath
是可选的。
第三步,也是可选的步骤,是调用
closePath()
. 此方法尝试通过从当前点到起点绘制一条直线来关闭形状。如果形状已经关闭或列表中只有一个点,则此函数不执行任何操作。
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);
推荐阅读
- java - 创建并有机会从字符串池中创建字符串对象有什么意义
- sql - Oracle 是否允许对分区进行求和,但仅当它遵守某些条件时才允许,否则使用滞后?
- c# - 如何使用 onclick 属性 c# webbrowser 单击按钮?
- python - Kivy 2 行标签文本
- byte-buddy - 如何使用 ByteBuddy 的 InvokeDynamic 类调用虚拟方法句柄?
- c# - 数据库似乎在执行期间更新,然后更改消失
- c - 使用函数交换两个变量的值时,为什么我应该以地址而不是实际变量名为目标?
- ansible - Ansible-playbook - 如何在字符串中添加大写
- java - Maven项目中的Logback
- discord - 试图制作一个机器人来计算语音频道中的成员