Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 644
Brian Avatar asked Feb 26 '26 04:02

Brian


1 Answers

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)
}
like image 124
Hans Felix Ramos Avatar answered Feb 28 '26 18:02

Hans Felix Ramos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!