The next time you walk down the supermarket or look at your hands - you need to pay attention - fractals are all around you. Fractals are natures patterns.
This example is about using your compute shader to write to a texture which is directly copied to the HTML Canvas. You can use texture buffers, not just numerical ones. Write a fractal patttern to the texture (fractal) and send it to a canvas output.
On the journey to mastering WebGPU compute - the journey should start with something simple - data read/write to the compute!
The hello world of fractals is the Mandelbrot set. Named after mathematician Benoit B. Mandelbrot.
The fractal algorithm is built on iterative equation \( z_{n+1} = z_n^2 + c \), where \( z \) and \( c \) are complex numbers and \( n \) is an integer.
A valid Mandelbrot set is for all values of \( c \) for which the sequence remains bounded. Its boundary, when visualized, reveals an beautifully detailed and self-similar pattern with infinite complexity, with each zoom revealing smaller versions of the entire set.
The beauty and complexity of the Mandelbrot set is sure to captivate you while giving you insights into the power of compute shaders.
WARNING For those who are fairly inexperienced in programming and think jumping into JavaScript and parallal programming - I'd strongly caution you to go back and get a lot of experience writing small test programs - to get a feel for things.
Fractal output for the listing below.
Complete Code
Let's go through the complete fractal program step by step. We start off by creating an output log function - just to record any data/information (send it to the output browser - instead of hiding it away in the console log window). We then check that we have the WebGPU API (and it's enabled).
If successful, we get hold of the adapter and the device.
let div = document.createElement('div'); document.body.appendChild( div ); div.style['font-size'] = '20pt'; function log( s ) { console.log( s ); let args = [...arguments].join(' '); div.innerHTML += args + '<br><br>'; }
log('WebGPU Compute Example');
if (!navigator.gpu) { log("WebGPU is not supported (or is it disabled? flags/settings)"); return; }
The fractal output will be copied to a HTML canvas. We create a canvas and get a suitable WebGPU context. The output texture from the compute shader will be directly copied to the canvas texture memory. The context needs to have additional flags set in the configuration to allow copying.
In this example, we also force the presentation format to be
rgba8unorm
- so it will be the same as the texture format we create on the compute shader.
Visitor:
Copyright (c) 2002-2025 xbdev.net - All rights reserved.
Designated articles, tutorials and software are the property of their respective owners.