I made this little script that makes an image bounce up and down (which is working fine).

Now I'm trying to add more images (more instances of that object) on my canvas, but for some reasons it's still showing only one.

If someone could spot what I'm missing, it would be appreciated.

var img = function() {

    this.props = {
        x: Math.floor(Math.random() * W + 1),
        y: 50,

        radius: 40,

        // Velocity
        vy: 1,

        // angle
        angle: 0,
        direction: 1
    };

    var self = this;

    this.draw = function() {
        ctx.drawImage(im, self.props.x, self.props.y);
    },

    this.update = function() {
        ctx.clearRect(0, 0, W, H);

        self.draw();

        self.props.y += self.props.vy;
        self.props.vy += gravity;

        if(self.props.y + self.props.radius > H) {
            self.props.y = H - self.props.radius;
            self.props.vy *= -bounceFactor;
            self.props.direction *= -1;
        }
    };

};

// my instances
var el = new img();
var el2 = new img();
var el3 = new img();

function main() {
    el.update();
    el2.update();
    el3.update();
}

setInterval(main, 1000/60);

Here's the full code: FIDDLE

有帮助吗?

解决方案

You clear the while canvas for all cars, so only the last one can be shown.
Just clear once in your main() function.

其他提示

You're using single image instance in DOM ... your fiddle is using src from closure scope referring to single image instance.

EDIT: In your code here im isn't actually referring to something, but it is shared among all instances of img().

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top