3

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.

1 Answer 1

1

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)
}
Sign up to request clarification or add additional context in comments.

3 Comments

This doesn't seem to work. I'm also not sure if this needs to be called within onload because this code is being executed in vue's created portion of the lifecycle, which seemingly does the same as using onload Also, you are using img two times, and imgObj two times, but imgObj is not defined. Are all four of those instances supposed to be the same variable?
If you create a new Image, It won't be loaded by the time they are added to the canvas.
This works. I'm not sure what I was doing wrong before. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.