简体   繁体   中英

Trouble using HTML Canvas with Vue.js

I am trying to upload an image using HTML canvas. The reason that I am using canvas, is because depending on the data I get back from the api, I will be super-imposing other little images over it, and this seems easier to do in canvas.

I am trying to create a new html image like this:

    const imgObj = new Image()
    imgObj.src = '../../pic'
    ctx.drawImage(imgObj, 200, 200) 

When I try to use this code in vue.js (as part of a javscript function called during the "onCreate" part of the life cycle), I am told that Image() is not defined.

So instead I have tried this:

    const imgObj = document.createElement('img')
    imgObj.src = '../../pic'
    ctx.drawImage(imgObj, 20, 20)

As far as I understand it, this should do that same thing, but nothing renders when I do this.

If I simply insert an <img> into the html, the picture loads, just fine, but as I said above, I will be overlapping a bunch of smaller photos on top, and working with a bunch of images seems a lot easier to manage with canvas.

Any advice is appreciated.

In your second way, you need to call drawImage inside onload function:

const imgObj= document.createElement('img')
imgObj.src = '../../pic'

imgObj.onload = function () {
   ctx.drawImage(imgObj, 20, 20)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM