I have a canvas and I wish to draw an icon on it. I'm aware you have to wait for the image to load before attempting to draw the image however nothing I've tried has worked.
I've attempted to use the full image URL (protocol, domain, and path), I've moved everything around, nothing has worked.
I've been Googling around for the better part of an hour and pretty much every solution involves making sure that the image loads first.
Here are a couple of snippets of what I have.
const image = new Image()
image.addEventListener('load', _ => {
addImage(canvas, image, coords)
})
image.src = '/images/image-location.svg'
function addImage(canvas, image, coords) {
const ctx = canvas.getContext('2d')
ctx.save()
ctx.drawImage(image, 0, 0, image.width, image.height, ...coords, 50, 50)
ctx.restore()
}
I threw a console.log
within the event listener just to make sure it was firing and it does indeed fire. I even logged inside addImage
and it definitely gets that far.
What is the solution to this?
I figured out the issue I was having here. I needed to add width
/height
attributes to the SVG element I was using as an image.