Reputation: 43
I want to draw a image using canvas but I got this error from browser:
Uncaught TypeError: Cannot read property 'drawImage' of undefined at Image.img.onload (test.js:23)
I put some messages on console.log() to help and the result is this:
args: 0 50 100
canvas: <canvas width="320" height="320">
this.img.src: http://localhost:3000/img/img1.jpg
this.ctx: undefined
Uncaught TypeError: Cannot read property 'drawImage' of undefined at Image.img.onload (test.js:23)
The problem is undefined "this.ctx" but I don't know why. Someone can help me please ? Below my code:
My .js:
var myVm = new Vue({
el: '#draw-image-test',
data: {
items: [
{ id: 1, src: 'img/img1.jpg' },
{ id: 2, src: 'img/img2.jpg' },
{ id: 3, src: 'img/img3.jpg' }
]
},
methods: {
drawItem(index, x, y) {
console.log('args:', index, x, y);
this.canvas = this.$refs.canRef;
console.log("canvas:", this.canvas);
this.ctx = this.canvas.getContext('2d');
this.img = new Image();
this.img.src = this.items[index].src;
console.log('this.img.src:', this.img.src);
this.img.onload = function () {
console.log('this.ctx:', this.ctx);
this.ctx.drawImage(this.img, x, y);
}
}
}
});
My HTML:
<div id="draw-image-test">
<canvas width="320" height="320" ref="canRef"></canvas>
<button v-on:click="drawItem(0, 50, 100)">Draw item 0</button>
</div>
Upvotes: 1
Views: 3813
Reputation: 43
I want to share the answer from Jayesh that works perfectly:
The problem is with on load function, this cannot be accessed with the on load function. Either you can use arrow function or define a local variable for this and access that within on load function.
this.img.onload = () => {
console.log('this.ctx:', this.ctx);
this.ctx.drawImage(this.img, x, y);
}
or
drawItem(index, x, y) {
const self = this;
.
.
.
this.img.onload = function () {
console.log('ctx:', self.ctx);
self.ctx.drawImage(self.img, x, y);
}
Upvotes: 0
Reputation: 1
Assign this
component instance to a global variable vm
and use it inside the callback as follows :
console.log('this.img.src:', this.img.src);
let vm=this;
this.img.onload = function () {
console.log('vm.ctx:', vm.ctx);
vm.ctx.drawImage(vm.img, x, y);
}
}
Upvotes: 1