如何防止更新圆圈的颜色?

时间:2017-12-19 14:46:27

标签: javascript

我想在画布上随机移动制作100个不同颜色的球。现在,我遇到了一个问题,每当我调用 this.update()进一步调用 this.draw()时,它都会更新 c。 fillStyle 属性,它保存随机生成的colors.Hence,它不断更新圆的颜色。 当调用者是 this.update()时,有什么方法可以阻止 c.fillStyle 更新吗?

var canvas = document.querySelector('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var c = canvas.getContext('2d');
var dx = 5;
var dy = 5;
function Circle(x, y, dx, dy, radius) {
    this.x = x;
    this.y = y;
    this.dx = dx;
    this.dy = dy;
    this.radius = radius;
    this.draw = function() {
        var i = 0
        c.beginPath();
        c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
        c.fillStyle = '#' + Math.floor(Math.random()*16777215).toString(16);
        c.fill();
    }
    this.update = function() {


            if ((this.x + this.radius) >innerWidth || (this.x - this.radius) < 0) {
                this.dx = -this.dx;
            }
            this.x += this.dx;
            if ((this.y + this.radius) >innerHeight || (this.y - this.radius) < 0) {
                this.dy = -this.dy;
            }
            this.y += this.dy;
            this.draw();
        }    
}
var circles = [];
for (var i = 0; i < 100; i++) {
    var radius = 30;
    var x = Math.random() * (window.innerWidth-2*radius)+radius;
    var y = Math.random() * (window.innerHeight-2*radius)+radius;
    circles.push(new Circle(x, y, dx, dy,  radius));     
}
function animate() {
         requestAnimationFrame(animate);
         c.clearRect(0,0, innerWidth,innerHeight);            
         for(var i = 0; i< circles.length;i++)
              circles[i].update();
     }
     animate();

3 个答案:

答案 0 :(得分:1)

您可以简单地存储颜色,以便保持一致:

     this.draw = function() {
       c.beginPath();
       c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
       c.fillStyle = this.color || ( this.color = "#" + Math.floor(Math.random()*16777215).toString(16));
       c.fill();
    }

一些解释:

 this.color || (..

意味着它应该采用this.color,如果不存在,它应该评估以下部分并采取:

 this.color = ...

然后存储颜色。

答案 1 :(得分:1)

与Jonas W.相同,但您可以将颜色存储在draw方法之外(恕我直言:它更干净):

this.fillStyle = '#' + Math.floor(Math.random()*16777215).toString(16);
this.draw = function() {
    var i = 0
    c.beginPath();
    c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
    c.fillStyle = this.fillStyle;
    c.fill();
}

答案 2 :(得分:0)

您必须在实例化新圆之前计算颜色,并将颜色计算传递给构造函数。 IE:

class Foo<B extends Bar> {
    B[] bs;
    Foo(Class<B> clazz, Stream<B> stream) { // General ctor
        bs = someFunctionOf(clazz, stream);
    }
    // FIX THIS ----+
    //              |
    //              ˅
    Foo(Class<Something> clazz) { // Special ctor
        // Can we make this work so Something is a Bar and an enum
        // and we can call the other constructor like this?
        this(clazz, Arrays.stream(clazz.getEnumConstants());
    }
}