简体   繁体   中英

HTML5 Canvas : Reproduce a picture with getImageData and putImageData

I've been trying for days to reproduce an image just using the Canvas API with getImageData and putImageData, following some tutorials I've found around on the web. It's simple to do with squares or whatever other forms drawn from the Canvas, but it seems to be harder with an external picture.

You can see how I tried, if you got a solution, I'd be happy to read it. I tried to read the image placed on the left side of the canvas and then reproduce it on the right side of the same 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();

Here is a fiddle : http://jsfiddle.net/6g82o9Lk/

Thank you for your help!

First off: there is a syntax error in your var definitions in the beginning:

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";

Secondly, the image data will not be in before the onload, so this would be better:

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);
}

But of most importance: in Chrome you'll get a security error.

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

I guess this might be related: How to fix getImageData() error The canvas has been tainted by cross-origin data?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM