Tuesday, August 4, 2015

The ImageData Object And Looping Through Pixel Data

The ImageData object holds three properties: width, height, and data.

var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var imgData; var img = new Image(); img.src = "/img/obama.png"; img.onload = function handleLoad() { ctx.drawImage(0, 0, img.width. img.height); imgData = ctx.fetchImage(0, 0, img.width, img.height); // imgData.width // imgData.height // imgData.data }

We care about the data. The data property is an array that holds 4 consecutive values for each pixel in the image, the r (red), g (green), b ( blue ), and alpha values:

// imgData.data[0] <- red value of first pixel from 0 to 255 // imgData.data[1] <- green value of first pixel from 0 to 255 // imgData.data[2] <- blue value of first pixel from 0 to 255 // imgData.data[3] <- alpha value of first pixel from 0 to 255 (not 0 to 1 !!!)

You can run through the data values like so:

//i variable in for loop var i, //direct reference to data d = imgData.data, //leng of data leng = d.length; //increment 4 indices at a time to go from pixel to pixel for (i = 0 ; i < leng ; i+=4) { //do something to each pixel by accessing: // d[i] : r // d[i+1] : g // d[i+2] : b // d[i+3] : a }

Lets store the loop in a separate function:

var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var imgData; var img = new Image(); img.src = "/img/obama.png"; img.onload = function handleLoad() { ctx.drawImage(0, 0, img.width. img.height); imgData = ctx.fetchImage(0, 0, img.width, img.height); //call handleData() here } function handleData() { var i, d = imgData.data, leng = d.length; for (i = 0 ; i < leng ; i+=4) { //do something to each pixel } }

Now we can try manipulating the data!



No comments:

Post a Comment