Pixel Manipulation on Canvas

Published :
Author :
Adam Khoury
In this JavaScript canvas programming exercise you will learn to use the Pixel Manipulation methods and properties. Pixel manipulation is useful for copying the pixels in a specified rectangular region on the canvas, and for creating new blank ImageData objects you can fill with image data. <!DOCTYPE html> <html> <head> <style> body{ margin:10px; background:#666; } #my_canvas{ background:#FFF; border:#000 1px solid; } </style> <script> var pic = new Image(); pic.src = "pink_ladybug.jpg"; function draw(){ var ctx = document.getElementById('my_canvas').getContext('2d'); ctx.drawImage(pic, 0, 0); ctx.fillStyle = "magenta"; ctx.fillRect(20, 20, 100, 100); ctx.fillStyle = "blue"; ctx.fillRect(40, 40, 100, 100); var src = ctx.getImageData(0, 0, 100, 100); var copy = ctx.createImageData(src.width, src.height); // Make the copy's data array equal to the src data array for(var i = 0; i < copy.data.length; i++){ copy.data[i] = src.data[i]; } // copy.data.set(src.data); // Use this when IE respects set() ctx.putImageData(copy, 250, 20); } window.onload = draw; </script> </head> <body> <canvas id="my_canvas" width="500" height="350"></canvas> </body> </html>