创建 javascript 个图像为 属性 的对象
Create javascript object with image as property
我对 javascript 比较陌生,我以前只用 Python 编程过,我很难用这种语言创建对象实例。
class SteeringWheel {
constructor(id) {
this.id = id;
this.can = document.getElementById(this.id);
this.ctx = this.can.getContext('2d');
this.img = new Image();
//some img
this.img.src = "https://images-na.ssl-images-amazon.com/images/I/41iNBF9Q%2BsL._SX425_.jpg";
this.img.onload = function() {
this.ctx.drawImage(this.img, 0, 0);
}
}
var st = new SteeringWheel('st1')
但是出现如下错误:
Uncaught TypeError: Cannot read property 'drawImage' of undefined
我尝试嵌套 onload 函数,但它不起作用。
this.ctx.onload = function() {
this.img.onload = function() {
this.ctx.drawImage(this.img, 0, 0);
}
}
在我的 .html 文件中有一个 ID 为 'st1' 的 canvas。在我调用上面写的脚本之后。
之所以创建对象是因为我以后打算调用:
var st = new SteeringWheel('st2')
var st = new SteeringWheel('st3')
并且拥有同一对象的多个实例。
这可能是一个愚蠢的问题,但我完全被阻止了。
你能试试这个吗
this.img.onload = () => {
this.ctx.drawImage(this.img, 0, 0);
}
因为发生 this
= this.img
。当与旧的 function () {}
方法一起使用时,这是正确的。但这在使用箭头函数时不适用。
我对 javascript 比较陌生,我以前只用 Python 编程过,我很难用这种语言创建对象实例。
class SteeringWheel {
constructor(id) {
this.id = id;
this.can = document.getElementById(this.id);
this.ctx = this.can.getContext('2d');
this.img = new Image();
//some img
this.img.src = "https://images-na.ssl-images-amazon.com/images/I/41iNBF9Q%2BsL._SX425_.jpg";
this.img.onload = function() {
this.ctx.drawImage(this.img, 0, 0);
}
}
var st = new SteeringWheel('st1')
但是出现如下错误:
Uncaught TypeError: Cannot read property 'drawImage' of undefined
我尝试嵌套 onload 函数,但它不起作用。
this.ctx.onload = function() {
this.img.onload = function() {
this.ctx.drawImage(this.img, 0, 0);
}
}
在我的 .html 文件中有一个 ID 为 'st1' 的 canvas。在我调用上面写的脚本之后。
之所以创建对象是因为我以后打算调用:
var st = new SteeringWheel('st2')
var st = new SteeringWheel('st3')
并且拥有同一对象的多个实例。
这可能是一个愚蠢的问题,但我完全被阻止了。
你能试试这个吗
this.img.onload = () => {
this.ctx.drawImage(this.img, 0, 0);
}
因为发生 this
= this.img
。当与旧的 function () {}
方法一起使用时,这是正确的。但这在使用箭头函数时不适用。