Reputation: 13
I can't get this bit of simple code to work. Can't see why.
$(document).ready(function() {
function convertImageToCanvas(image) {
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
canvas.getContext("2d").drawImage(image, 0, 0);
return canvas;
}
$('.img-class').each(convertImageToCanvas);
});
What am I doing wrong?
Upvotes: 0
Views: 138
Reputation: 1
Try
$(document).ready(function() {
// `i` : `index` , `image` : `DOM` `img` `element`
function convertImageToCanvas(i, image) {
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0);
// do stuff
};
$('.img-class').each(convertImageToCanvas);
});
jsfiddle http://jsfiddle.net/guest271314/rw8brh01/
See .each()
Upvotes: 1
Reputation: 4233
You should replace the image
var by this
. The image
var that you pass by param represents an index. The this
value represent the image element.
Note that you are just only creating the canvas element. You should append the canvas to another DOM element to see it rendered in the browser.
$(document).ready(function() {
function convertImageToCanvas() {
var canvas = document.createElement("canvas");
canvas.width = this.width;
canvas.height = this.height;
canvas.getContext("2d").drawImage(this, 0, 0);
return canvas;
}
$('.img-class').each(convertImageToCanvas);
});
Take a look at this codepen.
Upvotes: 0