- Ray Casting
- Fast Canvas Drawing
- Back to basics - Binary search
- Back to basics - Bubble sort
- Remote machine development
- WebAssembly In The Browser
- WebAssembly Brief Intro
- The Programming Metagame
- Raspberry Pi Zero Cluster
Fast Canvas Drawing
Let's findout what is the fastest way to draw a complete 640x480 canvas while accessing each pixel individually.
Here is the canvas that the code examples bellow will target, it is sinple black rectangle for now, and it will change colors after the fill implementations are run.
fillRect function, that one can be seen below:
Filling the canvas pixel-by-pixel
This first implementation uses
fillRect again, but to make it work as a single pixel, the
height are set to 1.
It was kind of expected but still a bit surprising that the multiple calls to
fillRect are very slow to completely fill the canvas pixel by pixel.
Using a bitmap
For this one, the code first creates a
Uint8ClampedArray that is set to the desired color byte by byte. And when done, it is drawn to the
canvas using the
This is a very fast implementation that can still be optimized a little bit, if what we want is to make updates to the pixels of the image frequently, then it would be much better to keep the array between frames and not create a new one every time.
Using a Uint32Array
For this implementation, the code is similar to the previous one, but instead of creating a
Uint8ClampledArray it creates a
Uint32Array that allow us to access four bytes at a time.
It is not much faster that the previous code that accessed the bytes individually but still comes up ahead most of the time, at least in my tests it is usually 0.5ms faster, which is nonetheless usable.
Uint32Array shows to be fast enough to potentially allow for a steady framerate, without bringing in more involved alternatives like WebGL or WebAssembly.