Now that we know how to access image data, including the RGBA for every pixel in an image or video, our next step is to explore the possibilities of pixel manipulation. In this recipe, we'll invert the colors of an image by inverting the color of each pixel.
Note
WARNING: This recipe must be run on a web server due to security constraints with the getImageData()
method.
Follow these steps to invert the colors of an image:
window.onload = function(){ var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d");
Create an
image
object and set theonload
property to a function that draws the image and gets the image data:var imageObj = new Image(); imageObj.onload = function(){ var sourceWidth = this.width; var sourceHeight = this.height; var sourceX = canvas.width / 2 - sourceWidth / 2; var sourceY = canvas.height / 2 - sourceHeight...