画布上对象的多个实例

several instances of object on canvas

本文关键字:实例 对象      更新时间:2023-09-26

我做了这个小脚本,使图像上下弹跳(工作正常)。

现在我正在尝试在我的画布上添加更多图像(该对象的更多实例),但由于某些原因,它仍然只显示一个。

如果有人能发现我错过了什么,将不胜感激。

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

这是完整的代码:小提琴

清除所有汽车的 while 画布,因此只能显示最后一辆。
只需在 main() 函数中清除一次。

你在 DOM 中使用单个图像实例...您的小提琴正在使用闭包范围内的src引用单个图像实例。

编辑:在您的代码中,im实际上并不是指某些东西,而是在所有img()实例之间共享。