Я хочу нарисовать изображение, используя холст, но я получил эту ошибку из браузера:
Uncaught TypeError: Cannot read property 'drawImage' of undefined at Image.img.onload (test.js:23)
Я поместил некоторые сообщения в console.log (), чтобы помочь, и результат такой:
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)
Проблема в undefined "this.ctx" , но я не знаю почему. Кто-нибудь может мне помочь, пожалуйста? Ниже мой код:
Мой. 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);
}
}
}
});
Мой 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>