HTML5 Canvas:使用getImageData和putImageData重现图片

时间:2015-02-18 10:05:39

标签: javascript image canvas getimagedata putimagedata

我已经尝试了几天使用Canvas API和getImageData以及putImageData重现图像,我已经在网上找到了一些教程。使用正方形或从Canvas中绘制的任何其他形式很简单,但外部图片似乎更难。

你可以看到我的尝试方式,如果你有解决方案,我会很高兴看到它。 我试图读取放在画布左侧的图像,然后在同一画布的右侧重现它。

var c       = document.getElementById("canvas"),
    ctx     = c.getContext('2d');
    img     = new Image(),
    img.src = "http://nagisalloum.com/wp-content/uploads/2012/01/white-duck-water2.jpeg";

img.onload = function(){
    ctx.drawImage(img, 0, 0, 400, 300);
}


//read the width and height of the canvas
var width   = c.width,
    height  = c.height,
    w2      = width / 2,
    imgData = ctx.getImageData(0, 0, 400, 300);

function drawing(){
    var index= (height * w2) * 4;   
    for(index= 0; index<=imgData.data.length; index+=4){
        red     = imgData.data[index];
        green   = imgData.data[index+1];
        blue    = imgData.data[index+2];
        alpha   = imgData.data[index+3]; 
    }
        ctx.putImageData(imgData, w2, 300);
}

drawing();

这是一个小提琴:http://jsfiddle.net/6g82o9Lk/

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

首先关闭:开头的var定义中存在语法错误:

var c       = document.getElementById("canvas"),
    ctx     = c.getContext('2d'),
    img     = new Image();
img.src = "http://nagisalloum.com/wp-content/uploads/2012/01/white-duck-water2.jpeg";

其次,图像数据不会在onload之前出现,所以这样会更好:

img.onload = function(){
    ctx.drawImage(img, 0, 0, 400, 300);
    drawing();
}

function drawing(){
    //read the width and height of the canvas
    var width   = c.width,
    height  = c.height,
    w2      = width / 2,
    imgData = ctx.getImageData(0, 0, 400, 300);

    var index= (height * w2) * 4;   
    for(index= 0; index<=imgData.data.length; index+=4){
        red     = imgData.data[index];
        green   = imgData.data[index+1];
        blue    = imgData.data[index+2];
        alpha   = imgData.data[index+3]; 
    }
        ctx.putImageData(imgData, w2, 300);
}

但最重要的是:在Chrome中,您会收到安全错误。

Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.

我想这可能是相关的:How to fix getImageData() error The canvas has been tainted by cross-origin data?