JavaScript Canvas - Image Processing
Monday, 07 October 2019
Article Index
JavaScript Canvas - Image Processing
Augment ImageData
The Complete Program

The complete program is:

<!DOCTYPE html>
   <title>TODO supply a title</title>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width,
     function createCanvas(h, w) {
       var c = document.createElement("canvas");
       c.width = w;
       c.height = h;
       return c;
     function imgLoaded(img) {
       return new Promise(
        function (resolve, reject) {
          img.addEventListener("load", function () {
     function augmentImageData(o) {
       o.getPixel = function (x, y) {
         var i = (x + y * this.width) * 4;
         return {R:[i],
                 G:[i + 1],
                 B:[i + 2],
                 A:[i + 3]
       o.setPixel = function (x, y, c) {
         var i = (x + y * this.width) * 4;[i] = c.R;[i + 1] = c.G;[i + 2] = c.B;[i + 3] = c.A;
  async function draw() {
   var ctx = document.body.appendChild(
createCanvas(400, 400)).getContext("2d"); var img = new Image(); var url = new URL("jeep.jpg",
"http://server/Filter/"); img.src = url; await imgLoaded(img); ctx.drawImage(img, 0, 0, 400, 300); var ImDat = ctx.getImageData(0, 0, 400, 300); augmentImageData(ImDat); for (var x = 0; x < 400; x++) { for (var y = 0; y < 300; y++) { var c1 = ImDat.getPixel(x, y); var c2 = ImDat.getPixel(x, y + 3); var r = Math.abs(c1.R - c2.R) + 128; var g = Math.abs(c1.G - c2.G) + 128; var b = Math.abs(c1.B - c2.B) + 128; var gray = (r + g + b) / 3; ImDat.setPixel(x, y,{R: gray, G: gray,
B: gray, A: c1.A}); } } ctx.putImageData(ImDat,0,0); } draw(); </script> </body> </html>

You can try the program out here.

A Security Problem

You can try loading images for this filter from the local file system, but if you do you will discover that it doesn't work. You cannot access the pixels of an image that has been loaded from a different URL and accessing pixels of a local file is strictly forbidden. If you download the file from a server with the same URL as the script then there's no problem.

To allow for testing, Chrome has a command line switch that turns off the security check - no doubt other browsers have similar features. All you have to do is locate the shortcut that you use to launch Chrome and change the target to read:

"C:\Program Files\Google\Chrome\Application\chrome.exe" 

Alternatively simply use the command from the command prompt or add:


to whatever command initiates Chrome. With this command line switch it all works and you can see the result of the effect.

Sections in book but not in this extract:

  • The Filter API

  • Convolution Filter

  • Custom Convolution

  • Reading a PCX File

  • Processing the PCX File

  • Listing - Read a PCX File


  • The ImageData object allows direct access to the pixel data within a bitmap.

  • The pixel data is stored in the data array property which is a Uint8ClampedArray in RGBA order.

  • With direct access to the pixel data you can write filters which change the bitmap in controlled ways using functions formed from the surrounding pixels.

  • The new Filter API provides a range of predefined filters that you can use.

  • You can also use any of the SVG filters via the url filter.

  • The SVG filters include a general convolution filter which can be used to implement many standard and custom linear filters.

  • A convolution filter replaces the current pixel value with a weighted average of it and the pixels that surround it. The weighted average is specified as a convolution matrix or mask.

  • It is also fairly easy to implement a convolution filter directly using ImageData and direct pixel manipulation.

  • You can also arrange to read and process any graphics file format that you have the specification for using the standard techniques of reading files, bit manipulation and ImageData.

Now available as a paperback or ebook from Amazon.

JavaScript Bitmap Graphics
With Canvas




  1. JavaScript Graphics
  2. Getting Started With Canvas
  3. Drawing Paths
      Extract:  Basic Paths 
  4. Stroke and Fill
      Extract: Stroke Properties 
  5. Transformations
      Extract: Transformations 
  6. Text
      Extract: Text, Typography & SVG 
  7. Clipping, Compositing and Effects
      Extract: Clipping & Basic Compositing 
  8. Generating Bitmaps
      Extract:  Introduction To Bitmaps **NEW!
  9. WebWorkers & OffscreenCanvas
      Extract: OffscreenCanvas
  10. Bit Manipulation In JavaScript
  11. Typed Arrays
  12. Files, blobs, URLs & Fetch
  13. Image Processing
      Extract: ImageData 
  14. 3D WebGL
  15. 2D WebGL
    Extract: WebGL Convolutions 

Related Articles

Reading A BMP File In JavaScript

Getting Started With SVG

SVG, JavaScript and the DOM

Getting Started with Box2D in JavaScript






To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on, Twitter, Facebook or Linkedin.





or email your comment to:


Last Updated ( Monday, 07 October 2019 )