Canvas get / set image data

An example of getting and setting the pixels in a 2d canvas context and writing the colour spectrum to the pixel buffer.

by soulwire

HTML

<canvas id="canvas" width="200" height="200"></canvas>

JavaScript

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var width = canvas.width;
var height = canvas.height;

// Get the empty pixel data.
var data = ctx.getImageData(0, 0, width, height);
var pixels = data.data;

var x, y, r, g, b, a, i;

for (y = 0; y < height; y++) {
  
  for (x = 0; x < width; x++) {
    
    // Equation for finding the pixel at (x,y)
    i = (y * width + x) * 4;
    
    // Blend red from left to right.
    r = (x / width) * 255;
    
    // Blend green from top to bottom.
    g = (y / height) * 255;
    
    // Blend all channels with 50% blue.
    b = 128;
    
    // Assume 100% alpha!
    a = 255;
    
    // Write back to pixel data.
    pixels[i] = r;
    pixels[i+1] = g;
    pixels[i+2] = b;
    pixels[i+3] = a;
    
  }
  
}

// Dump pixels.
ctx.putImageData(data, 0, 0);