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



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

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

}
}

有没有一种方法可以设置图像高度并将其作为属性添加到类中?

如果不希望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;
}

相关内容

  • 没有找到相关文章

最新更新