Reputation: 5232
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 = document.createElement("img");
var reader = new FileReader();
reader.onload = function(e) {img.src = e.target.result};
var files = event.target.files;
reader.readAsDataURL(files[0]);
var canvas = document.createElement('canvas');
canvas.width = 100;
canvas.height = 100;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
fails with
NS_ERROR_NOT_AVAILABLE: Component is not available slice.call( docElem.childNodes, 0 )[0].nodeType;
in my test-browser Firefox. What could be wrong?
Update
Very strange: If I add a "alert(canvas);" as the 3rd last line (I do that sometimes for debugging, I know I could and should use console.log), the error does not appear, however, I still do not see anything from my image...
Upvotes: 0
Views: 5529
Reputation: 17122
image need to be loaded to be drawn on canvas :
var img = new Image()
img.onload = function () {
ctx.drawImage(img, 0, 0)
}
img.src="image.png"
in your exemple:
var img = document.createElement("img")
var reader = new FileReader()
var canvas = document.createElement('canvas')
canvas.width = 100
canvas.height = 100
var ctx = canvas.getContext("2d")
reader.onload = function(e) {
var img = new Image()
img.onload = function () {
ctx.drawImage(img, 0, 0)
}
img.src = e.target.result
}
var files = event.target.files
reader.readAsDataURL(files[0])
Upvotes: 4
Reputation: 173
If it's easier to you, you can load an image from your HTML:
<img id="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.
Upvotes: 1