Reputation: 395
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.
Upvotes: 3
Views: 618
Reputation: 4424
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)
}
Upvotes: 1