In this recipe, we'll explore another common pixel manipulation algorithm, converting colors to grayscale.
Note
WARNING: This recipe must be ran on a web server due to security constraints with the getImageData()
method.
Follow these steps to convert the colors of an image to grayscale:
Define the canvas context:
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 destX = canvas.width / 2 - sourceWidth / 2; var destY = canvas.height / 2 - sourceHeight / 2; var sourceX = destX; var sourceY = destY; context.drawImage(this, destX, destY); var imageData ...