预加载图像并将其尺寸设置为 class 的属性

Preloading images and setting their dimensions as properties of a class

我想创建一个 class,它将创建具有属性和图像的对象,并设置其属性。我想保持图像的比例,所以只有宽度将作为参数传递,高度应由 class 本身设置。

    var scaleFactor = 1;
    class Ships {
      constructor(img, x1, y1, width) {
        let image = new Image();
        image.src = img;
        this.img = image;
        this.x1 = x1 * scaleFactor;
        this.y1 = y1 * scaleFactor;
        this.width = width * scaleFactor;

//I want to set the image height keeping its original ratio

        image.onload = function() {
        this.height  = this.width * image.height / image.width;
        this.x2 = this.x1 + this.width;
        this.y2 = this.y1 + this.height;

//But here 'this' refers to the image element and so it adds the properties to the image element and not the class
        }
        this.draw = function () {
          ctx.drawImage(this.img, this.x1, this.y1, this.width, this.height);
        }
        
      }
    }

有没有办法设置图像高度并将其作为 属性 添加到 class?

如果您不希望 this 关键字在您的 onload 函数中引用图像,只需将其替换为箭头函数即可。这样,this 仍将引用函数外部的范围,如下所示:

image.onload = () => {
    this.height  = this.width * image.height / image.width;
    this.x2 = this.x1 + this.width;
    this.y2 = this.y1 + this.height;
}