As I attempt to create an image using canvas, my browser throws this error at me:
Uncaught TypeError: Cannot read property 'drawImage' of undefined at Image.img.onload (test.js:23)
To troubleshoot, I added some console.log() messages and here is the output:
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 root of the issue seems to be undefined "this.ctx", which perplexes me. Can anybody offer assistance? Below is the code snippet in question:
The JavaScript section:
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);
}
}
}
});
The HTML portion:
<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>