2
votes

I am just trying to get in the habit of pixel manipulation and it doesn't change anything.

I use the following loop to invert each pixel:

var newImage = context.createImageData(canvas.width, canvas.height);
var arr = context.getImageData(0, 0, canvas.width, canvas.height);
var pixels = arr.data;

for(var i = 0; i < pixels.length; i+=4){
    var r = 255 - pixels[i];
    var g = 255 - pixels[i + 1];
    var b = 255 - pixels[i + 2];
    var a = pixels[i + 3];
    newImage.data[i] = r;
    newImage.data[i + 1] = g;
    newImage.data[i + 2] = b;
    newImage.data[i + 3] = a;
}

yet when I try and clear the canvas and rewrite it, nothing happens:

context.clearRect(0, 0, canvas.width, canvas.height);
context.putImageData(newImage, 0, 0);

why is this not working? what am I doing wrong?

jsfiddle

1
I think you must place theses instructions into the onLoad callback of the image ;)Paul Rad
Also, unless you're running from johnchapple.com or have set the appropriate flags, you'll be blocked by the good-ole "Unable to get image data from canvas because the canvas has been tainted by cross-origin data" message.enhzflep

1 Answers

2
votes

The problem comes from the image (not yet loaded). Your code works (watch this fiddle without image - http://jsfiddle.net/B82nk/1/).

You must do something like this:

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
canvas.width = 500;
canvas.height = 322;

var image_obj = new Image(); 
image_obj.onload = function(){
    var newImage = context.createImageData(canvas.width, canvas.height);
    var arr = context.getImageData(0, 0, canvas.width, canvas.height);
    var pixels = arr.data;

    for(var i = 0; i < pixels.length; i+=4){
        var r = 255 - pixels[i];
        var g = 255 - pixels[i + 1];
        var b = 255 - pixels[i + 2];
        var a = pixels[i + 3];
        newImage.data[i] = r;
        newImage.data[i + 1] = g;
        newImage.data[i + 2] = b;
        newImage.data[i + 3] = a;
    }

    context.clearRect(0, 0, canvas.width, canvas.height);
    context.putImageData(newImage, 0, 0);
}

image_obj.src = 'http://www.johnchapple.com/jcwp/wp-content/uploads/2012/09/photography_quotes.jpg';