Skip to content Skip to sidebar Skip to footer

Canvas Drawimage Fails

I'm fairly new to Canvas so please excuse if this is to simple. I want to resize images prior to upload if the browser supports this using canvas. However, this code var img = docu

Solution 1:

image need to be loaded to be drawn on canvas :

var img = newImage()
img.onload = function () {
     ctx.drawImage(img, 0, 0)
}
img.src="image.png"

in your exemple:

var img = document.createElement("img")
var reader = newFileReader()

var canvas = document.createElement('canvas')
canvas.width = 100
canvas.height = 100var ctx = canvas.getContext("2d")

reader.onload = function(e) {
    var img = newImage()
    img.onload = function () {
        ctx.drawImage(img, 0, 0)
    }
    img.src = e.target.result
}

var files = event.target.files
reader.readAsDataURL(files[0])

Solution 2:

If it's easier to you, you can load an image from your HTML:

<imgid="imagetoload"src="myimage.jpg" /><script>var image = document.getElementById("imagetoload");
</script>

But the best way is to load them with javascript like Yukulélé said.

Post a Comment for "Canvas Drawimage Fails"