首页 > 解决方案 > 所有圆圈都以相同的颜色绘制

问题描述

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

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);

标签: javascriptcanvas

解决方案


您需要添加一个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);


推荐阅读