Learn more about Russian war crimes in Ukraine.

How to write an ArrayBuffer to a canvas

I’m playing with WebGPU. But it’s currently very bleeding-edge, and Chrome hasn’t implemented direct GPU integration with canvas yet. As a workaround to display stuff, WebGPU lets you read data as an ArrayBuffer, and we can write that ArrayBuffer to a canvas using the traditional 2d context. Here’s a canvas which I’ve written an ArrayBuffer to:

The ArrayBuffer is interpreted as pixel data as follows. Each pixel is four bytes: red, green, blue and alpha, in that order. Pixels are in “reading” order: top-to-bottom, left-to-right. The ArrayBuffer contains no image dimension metadata, or any other metadata. We provide these dimensions by wrapping the ArrayBuffer with an ImageData. We can then pass that to ctx.putImageData. To demonstrate, here’s the JavaScript that generated the canvas above:

const ctx = canvas.getContext('2d');

const WIDTH = 256;
const HEIGHT = 256;

const arrayBuffer = new ArrayBuffer(WIDTH * HEIGHT * 4);
const pixels = new Uint8ClampedArray(arrayBuffer);
for (let y = 0; y < HEIGHT; y++) {
  for (let x = 0; x < WIDTH; x++) {
    const i = (y*WIDTH + x) * 4;
    pixels[i  ] = x;   // red
    pixels[i+1] = y;   // green
    pixels[i+2] = 0;   // blue
    pixels[i+3] = 255; // alpha
  }
}

const imageData = new ImageData(pixels, WIDTH, HEIGHT);
ctx.putImageData(imageData, 0, 0);

What can computers do? What are the limits of mathematics? And just how busy can a busy beaver be? This year, I’m writing Busy Beavers, a unique interactive book on computability theory. You and I will take a practical and modern approach to answering these questions — or at least learning why some questions are unanswerable!

It’s only $19, and you can get 50% off if you find the discount code ... Not quite. Hackers use the console!

After months of secret toil, I and Andrew Carr released Everyday Data Science, a unique interactive online course! You’ll make the perfect glass of lemonade using Thompson sampling. You’ll lose weight with differential equations. And you might just qualify for the Olympics with a bit of statistics!

It’s $29, but you can get 50% off if you find the discount code ... Not quite. Hackers use the console!

More by Jim

Tagged #programming, #javascript, #web. All content copyright James Fisher 2020. This post is not associated with my employer. Found an error? Edit this page.