简单地将图像转换为画布不起作用

时间:2014-11-07 21:01:42

标签: javascript jquery html5-canvas

我无法使用这一点简单的代码。看不出原因。

$(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);

});

我做错了什么?

2 个答案:

答案 0 :(得分:1)

尝试

    $(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/

请参阅.each()

答案 1 :(得分:0)

您应该将image var替换为this。您通过param传递的image var代表索引this值代表图片元素

请注意,您只是创建canvas元素。您应该将画布附加到另一个DOM元素以查看它在浏览器中呈现。

$(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);

});

查看this codepen。