Как нарисовать изображение в vue js - PullRequest
0 голосов
/ 14 апреля 2020

Я хочу нарисовать изображение, используя холст, но я получил эту ошибку из браузера:

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>

Ответы [ 2 ]

1 голос
/ 14 апреля 2020

Назначьте this экземпляр компонента глобальной переменной vm и используйте его внутри обратного вызова следующим образом:

  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);
      }
    }
0 голосов
/ 15 апреля 2020

Я хочу поделиться ответом от Jaye sh, который отлично работает:


Проблема связана с функцией загрузки, к ней нельзя получить доступ с помощью функции загрузки , Вы можете использовать функцию стрелки или определить локальную переменную для этого и получить доступ к ней в функции загрузки.

this.img.onload = () => {
   console.log('this.ctx:', this.ctx);
   this.ctx.drawImage(this.img, x, y);
}

или

drawItem(index, x, y) {
const self = this;
.
.
.
this.img.onload = function () {
   console.log('ctx:', self.ctx);
   self.ctx.drawImage(self.img, x, y);
}
...