Today lets learn how to access individual pixel data on canvas, manipulate it and put it back on to the canvas.
Important Note: Each pixel is composed of 4-bytes.
index.html and myStyle.css file content are same as Linear Gradients in Canvas: HTML5
JavaScript file: Full code
myScript.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | window.onload = canvas; function canvas() { var myCanvas = document.getElementById("myCanvas"); if( myCanvas && myCanvas.getContext("2d") ) { var context = myCanvas.getContext("2d"); var imgSrc = document.getElementById("img"); context.drawImage(imgSrc, 0, 0, 350, 350); var image = context.getImageData(0, 0, 350, 350); var pixel = image.data; var init = 1; while(init < context.canvas.height){ for(var j = 0; j < 5; j++) { var row = (init + j) * context.canvas.width * 4; for(var i = 0; i < context.canvas.width * 4; i += 4) { pixel[row + i] = 255 - pixel[row + i]; //red pixel[row + i + 1]= 255 - pixel[row + i + 1]; //green pixel[row + i + 2] = 255 - pixel[row + i + 2]; //blue } } init += 15; } context.putImageData(image, 0, 0, 0, 0, 175, 350); } } |
We draw an image on to the canvas using drawImage() method. Once we draw the image, we get all the raw pixel data of the image using getImageData() method. Extract it’s data property(it’s a single dimension array of raw pixel data) and store it inside a variable called pixel.
To process the image data, we proceed executing until init is lesser than the height of the canvas. Inside the while loop we calculate the current row and it’s width and iterate till the entire row pixels are manipulated. We change the values of RGB and assign it back to those pixels selected using the loop.
Once the control is out of while loop, we put back the image using putImageData() method. We also play around with the optional parameters and put back a portion of the manipulated data on to the canvas.
Manipulating Raw Pixel Data in Canvas: HTML5
[youtube https://www.youtube.com/watch?v=0K-n1NEYB7U]
Image data access functions
createImageData(w, h); – Creates new image data with width w and height h.
createImageData(imgData); – Create new image data from an existing one.
getImageData(x, y, w, h); – Gets image data within given bounds.
putImageData(imgData, x, y); – Puts back the modified data on to the canvas.
putImageData(imgData, x, y, [Dx, Dy, Dw, Dh]); – Puts back the modified data on to the canvas, within the specified rectangle.