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

标签 javascript canvas

简单总结一下问题就是这样。我想在 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/

相关文章:

javascript - 控制多个 Canvas 动画

Javascript 颜色渐变

javascript - 如何使用 javascript 和模板构建 DOM?

javascript - 使用单个 ajax 耳语器影响两个文本框

javascript - HTML5 Canvas : Use context. isPointInPath(x, y) 用于具有更多路径的复杂形状

javascript - Canvas - Canvas 保存为图像后,橡皮擦在 Canvas 上绘制黑线

javascript - 如何解除动态元素的事件绑定(bind)?

javascript - 如何使用 `localStorage` 来存储整个页面?

javascript - HTML5 Canvas 分层

javascript - 无法绘制由 "content"或 "background-image"而不是 "src"指定的图像