0 Spicy Yoghurt | Last updated: 28 November 2026 | Creative coding tutorial
Image dithering in JavaScript: from a simple threshold to Floyd–Steinberg
Learn how Floyd–Steinberg dithering works by building it in JavaScript, and compare it with Bayer and Atkinson dithering. On an HTML5 canvas, reduce a photo to black and white or a retro color palette, such as the original Game Boy's four shades of green.
Drag the line across the photo to compare the original with the dithered version. To the right of the line, the photo has only two colors: black and white.
From a distance, the black and white dots blend into shades of gray, and you can still see the shine on the metal balls. By the end of this tutorial, you'll know how to do this yourself with Floyd–Steinberg dithering. Along the way, you'll compare it with other methods, reduce a photo to the colors of an old game console, and give a game a retro look.
What is dithering?
Sometimes you have fewer colors than an image needs. An old screen may show only black and white, a printer has just a few inks, and a GIF image can hold at most 256 colors. Dithering places the colors you do have in a fine pattern of dots. From a distance, your eyes blend the dots together, and you see the shades in between.
The demo below shows the same gradient three times, from black on the left to white on the right. The top strip has all 256 shades of gray. The middle strip has only black and white, and each pixel is rounded to the closest of the two. The bottom strip also has only black and white, but with dithering. Pick a zoom level to see the dots up close:
At 1×, the dithered strip looks almost like the real gradient, especially on a phone or other high-resolution screen, where each dot is tiny. Zoom in, and you can see how it works: the darker the gray, the more dots are black.
You've probably seen dithering before. The original Game Boy could show four shades, and the first Macintosh only black and white. Games and programs on both used dithering for shadows, gradients and photos. Newspapers print photos with a similar trick, called halftoning. And some modern games, such as Return of the Obra Dinn (2018), use dithering on purpose as part of their style.
Read and change pixels with getImageData() and putImageData()
To dither a photo, you need to read and change its pixels one by one. The code in this tutorial draws on an HTML5 canvas. canvas is the <canvas> element on your page, and context is its 2D drawing context. The tutorial on setting up an HTML5 canvas shows how to get both.
Load the photo with an Image object, and wait until it has loaded before you draw it. For more about loading images, see the tutorial on images and sprite animations. Then draw the photo on the canvas with drawImage(), and getImageData() gives you its pixels:
let photo = new Image();
photo.onload = function () {
context.drawImage(photo, 0, 0, canvas.width, canvas.height);
let pixels = context.getImageData(0, 0, canvas.width, canvas.height);
toGrayscale(pixels);
context.putImageData(pixels, 0, 0);
};
photo.src = 'photo.jpg';toGrayscale() is a function you'll write in a moment. pixels is an ImageData object. Its data holds four numbers for every pixel, row by row: red, green, blue and alpha, each from 0 to 255. When you've changed the pixels, putImageData() draws them back onto the canvas.
If you open your page straight from a file on your computer, some browsers treat photo.jpg as if it came from another website. Then getImageData() throws a security error. Test your page on a local server instead: use the Live Server extension in VS Code, or run npx serve in your project folder. A photo from another website gives the same error; a question at the end of this page explains why.
Before you can turn a pixel black or white, you need to know how bright it is. You might think you can take the average of red, green and blue. But your eyes see green as much brighter than blue, so this formula is closer to what you see:
function toGrayscale(pixels) {
let data = pixels.data;
for (let i = 0; i < data.length; i += 4) {
let gray =
0.299 * data[i] +
0.587 * data[i + 1] +
0.114 * data[i + 2];
data[i] = gray;
data[i + 1] = gray;
data[i + 2] = gray;
}
}The three numbers in the formula add up to 1, so white stays 255. The loop jumps four numbers at a time, from one pixel to the next. It sets red, green and blue to the same value, which makes the pixel gray, and it leaves alpha alone. data only holds whole numbers, so gray gets rounded when you store it. Here's the result. Pick a photo, and switch between the gray version and the color photo:
Turn every pixel black or white with a threshold
The simplest way to get only black and white is a threshold. Every pixel darker than the threshold becomes black, and every other pixel becomes white. Call toGrayscale() first, so red, green and blue are the same, and you only need to look at red:
function threshold(pixels, limit) {
let data = pixels.data;
for (let i = 0; i < data.length; i += 4) {
let value = data[i] < limit ? 0 : 255;
data[i] = value;
data[i + 1] = value;
data[i + 2] = value;
}
}
threshold(pixels, 128);Try it in the demo below, with three different thresholds:
In the demo, with a threshold of 128, the gray background behind the Newton's cradle turns white, and most of the shading on the balls is gone. The threshold rounds every pixel on its own and throws away how far that pixel was from black or white. A light gray pixel and a white pixel both become white. A lower threshold makes more pixels white, and a higher one makes more of them black. But no single threshold works for the whole photo.
The same thing happens with more colors. Round each pixel to the closest of 4 or 8 shades, and a smooth gradient turns into bands. This is called posterization, and you'll see it again in the section about color palettes.
Break up solid areas with random noise
One way to get the shades back is to add some randomness. Before you compare a pixel with the threshold, add a random number between -128 and 128 to it:
function randomDither(pixels) {
let data = pixels.data;
for (let i = 0; i < data.length; i += 4) {
let noise = (Math.random() - 0.5) * 256;
let value = data[i] + noise < 128 ? 0 : 255;
data[i] = value;
data[i + 1] = value;
data[i + 2] = value;
}
}Take a pixel with a brightness of 102, which is 40% of the way from black to white. It turns white when the noise is 26 or more, and that's 102 of the 256 possible values. So it becomes white about 40% of the time. On average, every part of the photo keeps its brightness.
Try it with different amounts of noise. High uses the noise from the code above, and Low uses half as much. Off is the plain threshold of 128 from the previous section:
The shading is back, but the photo looks grainy, like the snow on an old TV. Random numbers clump together: sometimes several white pixels land side by side, and sometimes there's a gap. With the noise on Low, more of the solid areas stay intact, but less of the shading comes back. Want to know more about Math.random()? The tutorial on random numbers in JavaScript explains how it works.
Use a Bayer matrix for ordered dithering
Instead of a random number, you can use a fixed pattern. Ordered dithering gives every pixel its own threshold from a small grid of numbers that repeats across the whole image. The best-known grid is the Bayer matrix, named after Bryce Bayer, who described it in 1973. A 4×4 Bayer matrix has the numbers 0 to 15, placed so that each number is as far as possible from all the numbers before it. That way, the white dots are spread out evenly at every brightness.
orderedDither() looks up the number for each pixel and turns it into a threshold:
function orderedDither(pixels, matrix) {
let data = pixels.data;
let size = matrix.length;
for (let y = 0; y < pixels.height; y++) {
for (let x = 0; x < pixels.width; x++) {
let i = (y * pixels.width + x) * 4;
let cell = matrix[y % size][x % size];
let limit = (cell + 0.5) * 256 / (size * size);
let value = data[i] < limit ? 0 : 255;
data[i] = value;
data[i + 1] = value;
data[i + 2] = value;
}
}
}Every row has pixels.width pixels. So the four numbers of the pixel in column x of row y start at index (y * pixels.width + x) * 4. x % size and y % size repeat the matrix: with a 4×4 matrix, pixel column 4 uses the same matrix column as pixel column 0. limit is the number from the matrix, turned into a threshold between 0 and 256. With a 4×4 matrix, the 16 thresholds are 8, 24, 40 and so on, up to 248. The + 0.5 puts each threshold in the middle of its step, so a pixel with a value of 0 stays black, and one with a value of 255 turns white.
Pick a matrix size in the demo. The code shows the matrix that the demo uses:
const matrix = [
[0, 8, 2, 10],
[12, 4, 14, 6],
[3, 11, 1, 9],
[15, 7, 13, 5]
];
orderedDither(pixels, matrix);A bigger matrix has more thresholds, so it can show more shades. With a 2×2 matrix, 0, 1, 2, 3 or all 4 pixels of every 2×2 block can be white: that's 5 shades. A 4×4 matrix shows 17 shades, and an 8×8 matrix 65.
You can build each bigger matrix from the one before it, starting with the 2×2 matrix [[0, 2], [3, 1]]:
- Copy - Put four copies of the smaller matrix in a square.
- Multiply - Multiply every number by 4.
- Add - Add 0 to the top-left copy, 2 to the top-right copy, 3 to the bottom-left copy and 1 to the bottom-right copy: the numbers of the 2×2 matrix itself.
Ordered dithering is fast, and each pixel only needs its own brightness and its position. That makes it a good fit for a shader, a small program that the graphics card runs for every pixel at the same time. And the pattern stays in place when the image changes, for example in an animation. The crosshatch look is typical of old computers and pixel art.
Spread the rounding error with Floyd–Steinberg dithering
Rounding a pixel to black or white makes it a little wrong. A pixel with a brightness of 100 becomes black, which is 0, so it's now 100 too dark. That difference is the rounding error. A threshold throws the error away. Error diffusion keeps it and adds it to the pixels that come next, so in this example, those pixels are more likely to turn white.
The best-known way to do this is Floyd–Steinberg dithering. Robert Floyd and Louis Steinberg published it in 1976. It goes through the pixels row by row, from left to right. After rounding a pixel, it splits the error among four neighbors:
- Right - 7/16 of the error goes to the next pixel in the same row.
- Below left - 3/16 goes to the pixel below and to the left.
- Below - 5/16 goes to the pixel directly below.
- Below right - 1/16 goes to the pixel below and to the right.
Together, that's 16/16, all of the error. So on average, the photo stays just as bright. The error only goes to pixels that come later, because the pixels before the current one are already done.
Step through it in the demo below. Each square is one pixel and shows its brightness. The square with the red border is the pixel that gets rounded. The squares with a blue border are the neighbors that get part of its error. The number at the top of each one is the fraction it gets:
A pixel with a value of 100 becomes black and passes on +100: its neighbors get lighter. A pixel with a value of 200 becomes white and passes on -55: its neighbors get darker. In a light gray area, the -55s add up over a few white pixels, until one pixel drops below 128 and turns black. So the area turns mostly white, with a black dot here and there.
In code, the error needs a place to go. You might be tempted to add it straight to pixels.data. But data is a Uint8ClampedArray: it only holds whole numbers from 0 to 255. A pixel with a value of 250 plus an error of 30 would be cut off at 255, and a value below 0 would become 0. So first copy the brightness values into a Float32Array, which can also hold negative numbers and fractions:
function floydSteinberg(pixels) {
let width = pixels.width;
let height = pixels.height;
let data = pixels.data;
let gray = new Float32Array(width * height);
for (let i = 0; i < gray.length; i++) {
gray[i] = data[i * 4];
}
function addError(x, y, amount) {
if (x >= 0 && x < width && y < height) {
gray[y * width + x] += amount;
}
}
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
let oldValue = gray[y * width + x];
let newValue = oldValue < 128 ? 0 : 255;
let error = oldValue - newValue;
gray[y * width + x] = newValue;
addError(x + 1, y, error * 7 / 16);
addError(x - 1, y + 1, error * 3 / 16);
addError(x, y + 1, error * 5 / 16);
addError(x + 1, y + 1, error * 1 / 16);
}
}
for (let i = 0; i < gray.length; i++) {
data[i * 4] = gray[i];
data[i * 4 + 1] = gray[i];
data[i * 4 + 2] = gray[i];
}
}gray has one number per pixel: the brightness from toGrayscale(). addError() adds part of the error to one pixel in gray, but only if that pixel is inside the image. The last loop copies the result back into data. Here's Floyd–Steinberg on a photo:
Compare this result with the threshold and random noise versions from earlier on this page. In the Newton's cradle photo, the background is gray again, the balls look round again, and the dots are spread out evenly, without clumps.
Compare other error diffusion methods
Floyd–Steinberg isn't the only way to spread the error. Other methods spread it over more neighbors, or give them different fractions. To try them, turn the fractions, also called weights, into a list. Each entry says how far to the right (x) and down (y) a neighbor is, and how much of the error it gets:
const floydSteinbergKernel = [
{x: 1, y: 0, weight: 7 / 16},
{x: -1, y: 1, weight: 3 / 16},
{x: 0, y: 1, weight: 5 / 16},
{x: 1, y: 1, weight: 1 / 16}
];A list like this is called a kernel. diffuseError() works like floydSteinberg(), but instead of four separate addError() calls, it loops over the kernel:
function diffuseError(pixels, kernel, serpentine) {
// ... the same start as floydSteinberg()
for (let y = 0; y < height; y++) {
let direction = serpentine && y % 2 == 1 ? -1 : 1;
for (let step = 0; step < width; step++) {
let x = direction == 1 ? step : width - 1 - step;
let oldValue = gray[y * width + x];
let newValue = oldValue < 128 ? 0 : 255;
let error = oldValue - newValue;
gray[y * width + x] = newValue;
for (let spot of kernel) {
let spotX = x + spot.x * direction;
addError(spotX, y + spot.y, error * spot.weight);
}
}
}
// ... the same end as floydSteinberg()
}Leave serpentine at false for now: you'll find out what it does below the demo. Pick a method, and the code shows its kernel:
const floydSteinbergKernel = [
{x: 1, y: 0, weight: 7 / 16},
{x: -1, y: 1, weight: 3 / 16},
{x: 0, y: 1, weight: 5 / 16},
{x: 1, y: 1, weight: 1 / 16}
];
diffuseError(pixels, floydSteinbergKernel, false);Here's what makes each method in the demo different:
- Atkinson - Bill Atkinson designed it at Apple, and the first Macintosh used it. It gives 1/8 of the error to six neighbors: two to the right, three in the row below, and one in the row after that. That adds up to only 6/8, so a quarter of the error disappears. In a very light area, the error never builds up enough to make a black dot, and in a very dark area, it never makes a white one. So the lightest areas turn completely white, and the darkest areas completely black. You lose detail there, but the image gets more contrast.
- Jarvis–Judice–Ninke - Spreads the error over 12 neighbors, up to two rows down. The result is smoother, but it takes more than twice as long as Floyd–Steinberg.
- Stucki - Uses the same 12 neighbors as Jarvis–Judice–Ninke, with different weights, and looks a little sharper.
- Sierra Lite - Uses only three neighbors, and is the fastest of these.
Pick Floyd–Steinberg in the demo and look closely at the smooth background. You may see dots that line up in short, curvy rows, sometimes called worms. They come from scanning every row from left to right, so the error always flows the same way.
Serpentine scanning breaks up the worms: it goes from left to right on one row and from right to left on the next. That's what serpentine does in diffuseError(): on every other row, direction is -1, the loop starts at the right, and spot.x * direction mirrors the kernel. Switch the demo to Serpentine to compare.
Dither a photo to a color palette
So far, every pixel has become black or white. With a palette, every pixel gets one of a few colors instead. A palette is an array of colors, each with a red, green and blue value from 0 to 255. Here's a set of four greens that looks like the screen of the original Game Boy:
const gameBoyPalette = [
[15, 56, 15],
[48, 98, 48],
[139, 172, 15],
[155, 188, 15]
];For every pixel, you need the color in the palette that's closest to it. Think of red, green and blue as the x, y and z of a point in space, and look for the nearest point. The real distance is the square root of dr * dr + dg * dg + db * db, where dr, dg and db are the differences in red, green and blue. You can skip the square root, because the color with the smallest squared distance also has the smallest distance. The tutorial about Voronoi diagrams uses the same trick. getClosestColor() checks every color in the palette:
function getClosestColor(red, green, blue, palette) {
let closest = palette[0];
let closestDistance = Infinity;
for (let color of palette) {
let dr = color[0] - red;
let dg = color[1] - green;
let db = color[2] - blue;
let distance = dr * dr + dg * dg + db * db;
if (distance < closestDistance) {
closestDistance = distance;
closest = color;
}
}
return closest;
}Dithering to a palette works like diffuseError() with floydSteinbergKernel, but with three errors per pixel: one each for red, green and blue. The colors array holds three numbers per pixel, and addColorError() adds part of an error to one of them: the red, green or blue value of a pixel. The photo doesn't need to be gray for this:
function ditherToPalette(pixels, palette) {
let width = pixels.width;
let height = pixels.height;
let data = pixels.data;
let colors = new Float32Array(width * height * 3);
for (let i = 0; i < width * height; i++) {
colors[i * 3] = data[i * 4];
colors[i * 3 + 1] = data[i * 4 + 1];
colors[i * 3 + 2] = data[i * 4 + 2];
}
function addColorError(x, y, channel, amount) {
if (x >= 0 && x < width && y < height) {
colors[(y * width + x) * 3 + channel] += amount;
}
}
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
let i = (y * width + x) * 3;
let color = getClosestColor(
colors[i], colors[i + 1], colors[i + 2], palette
);
for (let channel = 0; channel < 3; channel++) {
let error = colors[i + channel] - color[channel];
colors[i + channel] = color[channel];
for (let spot of floydSteinbergKernel) {
addColorError(
x + spot.x, y + spot.y, channel,
error * spot.weight
);
}
}
}
}
for (let i = 0; i < width * height; i++) {
data[i * 4] = colors[i * 3];
data[i * 4 + 1] = colors[i * 3 + 1];
data[i * 4 + 2] = colors[i * 3 + 2];
}
}This works well for a palette with lots of different colors, such as the PICO-8 palette. With the four Game Boy greens, though, things go wrong. The greens have almost no blue in them, so the blue in a photo can never be matched. The error in the blue channel keeps building up, and large parts of the photo turn into one flat green.
The original Game Boy didn't really show colors anyway, only four shades. So work the way the Game Boy did: convert the photo to grayscale, dither it to four grays, and swap each gray for the green at the same position in gameBoyPalette:
const grays = [
[0, 0, 0],
[85, 85, 85],
[170, 170, 170],
[255, 255, 255]
];
function ditherToGameBoy(pixels) {
toGrayscale(pixels);
ditherToPalette(pixels, grays);
let data = pixels.data;
for (let i = 0; i < data.length; i += 4) {
let green = gameBoyPalette[data[i] / 85];
data[i] = green[0];
data[i + 1] = green[1];
data[i + 2] = green[2];
}
}The grays are 0, 85, 170 and 255, so data[i] / 85 is 0, 1, 2 or 3: the position of the green that belongs to that gray.
The demo below has four palettes, and it uses ditherToGameBoy() for the Game Boy palette. The 8 colors (RGB) palette has black, white, red, green, blue, cyan, magenta and yellow: every combination of red, green and blue at 0 or 255. PICO-8 is a fantasy console: a made-up game console that runs on your computer. Its 16 colors are popular for pixel art.
Try the palettes, and turn dithering off to see what the palette alone does. You can also use your own photo. It stays in your browser, and nothing gets uploaded:
Without dithering, smooth areas turn into bands of one color: that's the posterization from the section about thresholds. With dithering, the colors mix, and you can see shades that aren't in the palette.
Use dithering in your game
Dithering gives a game the look of an old computer or console. Draw your game on a small canvas, dither it, and then draw it, scaled up, onto the canvas on your page. Set imageSmoothingEnabled to false, so the browser doesn't blur the pixels. The tutorial on setting up an HTML5 canvas explains this in the part about scaling up pixel art.
In the code below, screen is the small canvas: 250 by 133 pixels, about a third of the width and height of the 750 by 400 canvas on the page. willReadFrequently tells the browser that you'll read the pixels of screen often, which makes getImageData() faster. matrix is the Bayer matrix from earlier on this page. Call draw() every frame from your game loop:
let screen = document.createElement('canvas');
screen.width = 250;
screen.height = 133;
let screenContext = screen.getContext('2d', {willReadFrequently: true});
function draw() {
// Draw your game on screenContext here
let pixels = screenContext.getImageData(
0, 0, screen.width, screen.height
);
toGrayscale(pixels);
orderedDither(pixels, matrix);
screenContext.putImageData(pixels, 0, 0);
context.imageSmoothingEnabled = false;
context.drawImage(screen, 0, 0, canvas.width, canvas.height);
}Every frame, the demo below draws a ball lit by a lamp. Move your mouse over the demo, or touch it with your finger, and the lamp follows. Switch between the two methods while the lamp moves:
With Floyd–Steinberg, the dots crawl and flicker as the lamp moves. When one pixel changes, its error changes too, and that can shift every dot after it. With the Bayer matrix, each pixel only depends on its own brightness. So the pattern stays in place, and only the edge of the light moves. That's why games with a dithered look often use ordered dithering for anything that moves.
But when the camera moves, a pattern that stays in place on the screen seems to slide over everything. In Return of the Obra Dinn, a first-person game, you turn the camera all the time. So the game's maker, Lucas Pope, made the pattern stick to the world instead.
The Bayer matrix also gives you a nice transition. Click Fade out in the demo: the pixels turn black in the order of the matrix. fade goes from 0 to 1 during the transition, and every pixel whose number in the matrix is low enough turns black:
if ((cell + 0.5) / (size * size) < fade) {
value = 0;
}Put this if statement in the inner loop of orderedDither(), right after the line that sets value. cell is the number from the matrix that the loop already looks up. fade is a variable outside the function, so you can change it every frame. For example, add 0.02 to fade every frame until it reaches 1: at 60 frames per second, that takes less than a second.
Old games used a pattern like this to draw see-through shadows and water. They drew the shadow or water on every other pixel, so the background showed through the gaps.
Common questions about dithering
Why does my Floyd–Steinberg dithering look wrong?
First, check where you store the error. If you add it straight to pixels.data, the Uint8ClampedArray clamps every value to the range 0 to 255, and part of the error gets lost. Use a Float32Array, as in this tutorial. Also read each pixel from that array, not from the original photo. Otherwise, the error from the pixels before it never arrives. And make sure the error only goes to pixels that come later.
Why does getImageData() throw a security error?
The canvas has a photo from another website on it, so the browser marks the canvas as tainted and won't let your code read its pixels. This protects you: without it, a website could read images that only you can see, such as the ones on another site where you're logged in. Some browsers also treat a photo as coming from another website when you open your page straight from a file on your computer. Test your page on a local server instead. If the photo is on another website, copy it to your own site, or let the visitor pick a file, as the palette demo above does. A photo from another server also works if that server allows it: set the crossOrigin property of the Image to 'anonymous' before you set src.
Do I need to convert colors to linear RGB before dithering?
Not always. For pixel art or a retro look, the simple version in this tutorial is fine, and not everyone agrees that linear RGB looks better. The numbers in an image aren't proportional to the amount of light. A pixel with a gray value of 128 gives off only about a fifth as much light as a white one. So if you dither a gray value of 128 into half black and half white dots, the result looks lighter than it should. To get it right, convert the colors to linear RGB before you dither, and convert them back afterward. Dividing a value by 255 and raising it to the power of 2.2 comes close to the exact conversion.
What's the difference between ordered dithering and error diffusion?
Ordered dithering compares each pixel with a threshold from a repeating matrix, so it handles each pixel on its own. It's fast, works in a shader and stays still in an animation, but you can see the pattern. Error diffusion passes the rounding error on to the next pixels. It looks more natural on photos, but each pixel depends on the ones before it, so it's slower, and it flickers when the image moves.
Which dithering algorithm is the best?
It depends on what you need. For a photo, Floyd–Steinberg or Jarvis–Judice–Ninke with serpentine scanning gives the most natural result. Atkinson gives a crisp look with more contrast. For a game, a retro look or anything that moves, use ordered dithering with a Bayer matrix.
How do I dither an image to my own palette?
Put your colors in an array of red, green and blue values, and pass it to ditherToPalette(). getClosestColor() finds the nearest color for every pixel, and error diffusion does the rest. The dots can only mix colors that are in the palette. So a palette with a few dark and a few light colors works better than one with only light colors. If your palette is a few shades of one color, like the Game Boy's greens, dither the brightness instead, as ditherToGameBoy() does.
Why does dithering flicker in an animation?
With error diffusion, a small change in one pixel can change the error of every pixel after it, so the dots jump around from frame to frame. Ordered dithering doesn't have this problem, because each pixel only depends on itself. For something that doesn't move, like a background, you can also dither it once and keep the result.
Can I dither in a shader?
With ordered dithering, yes. A fragment shader can look up the threshold for its own pixel in the Bayer matrix, and the graphics card does all the pixels at the same time. Error diffusion is hard to do in a shader, because each pixel needs the error of the pixels before it, so they have to be done one after the other.
What is blue noise dithering?
Blue noise is random noise without clumps: the white and black dots are spread out evenly. A blue noise texture is an image with that kind of noise in it. You can use its gray values as the thresholds, instead of the numbers in a Bayer matrix. The result looks more natural, without the crosshatch, and it's just as fast. Making a good blue noise texture takes a lot of computation, so you usually load a ready-made one from a small image file.
Is dithering the same as halftoning?
They're close relatives. Halftoning is the printing version: a newspaper prints dots of different sizes on a grid, with big dots for a dark area and small dots for a light one. A screen can't change the size of a pixel, so dithering changes how many pixels get each color instead.
What does dithering mean in audio?
It's the same idea, but for sound. Digital audio is a long list of measurements of the sound wave. Each measurement is called a sample. When you save sound with fewer bits, every sample gets rounded, and you can hear the rounding error as a buzz or a crackle. Adding a little noise before rounding, like the random noise in this tutorial, turns that into a soft, even hiss.
Example code: image dithering
Here's an example page that puts the basics from this tutorial together in a single HTML file. It draws a sky, a sun and two hills, and dithers them with the method you pick. The file picker under the buttons lets you dither your own photo instead. You don't need a local server for this example: it draws its own scene, and browsers let your code read a photo from the file picker. Copy all of the code below into a new .html file and open that file in your browser:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Image Dithering Tutorial | Spicy Yoghurt</title>
</head>
<body>
<h1>Image dithering tutorial by Spicy Yoghurt</h1>
<canvas id="canvas" width="750" height="400" style="border:1px solid lightgray;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<p>
<button data-method="threshold">Threshold</button>
<button data-method="bayer">Bayer</button>
<button data-method="floydSteinberg">Floyd–Steinberg</button>
<button data-method="atkinson">Atkinson</button>
<button data-method="gameBoy">Game Boy</button>
</p>
<p>
Dither your own photo:
<input type="file" id="photo">
</p>
<script>
'use strict';
let canvas;
let context;
let original;
let method = 'floydSteinberg';
const matrix = [
[0, 8, 2, 10],
[12, 4, 14, 6],
[3, 11, 1, 9],
[15, 7, 13, 5]
];
const floydSteinbergKernel = [
{x: 1, y: 0, weight: 7 / 16},
{x: -1, y: 1, weight: 3 / 16},
{x: 0, y: 1, weight: 5 / 16},
{x: 1, y: 1, weight: 1 / 16}
];
const atkinsonKernel = [
{x: 1, y: 0, weight: 1 / 8},
{x: 2, y: 0, weight: 1 / 8},
{x: -1, y: 1, weight: 1 / 8},
{x: 0, y: 1, weight: 1 / 8},
{x: 1, y: 1, weight: 1 / 8},
{x: 0, y: 2, weight: 1 / 8}
];
const gameBoyPalette = [
[15, 56, 15],
[48, 98, 48],
[139, 172, 15],
[155, 188, 15]
];
const grays = [
[0, 0, 0],
[85, 85, 85],
[170, 170, 170],
[255, 255, 255]
];
window.onload = init;
function init() {
canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
drawScene();
original = context.getImageData(
0, 0, canvas.width, canvas.height
);
let buttons = document.querySelectorAll('[data-method]');
for (let button of buttons) {
button.addEventListener('click', function () {
method = button.getAttribute('data-method');
dither();
});
}
let input = document.getElementById('photo');
input.addEventListener('change', function () {
if (input.files.length > 0) {
loadPhoto(input.files[0]);
}
});
dither();
}
function drawScene() {
// A sky that gets lighter toward the horizon
let sky = context.createLinearGradient(0, 0, 0, 300);
sky.addColorStop(0, '#0099b0');
sky.addColorStop(1, '#ffe7a8');
context.fillStyle = sky;
context.fillRect(0, 0, canvas.width, canvas.height);
// A sun with a soft glow
let sun = context.createRadialGradient(
520, 150, 20, 520, 150, 160
);
sun.addColorStop(0, 'white');
sun.addColorStop(0.3, '#ffcf51');
sun.addColorStop(1, 'rgba(255, 207, 81, 0)');
context.fillStyle = sun;
context.fillRect(0, 0, canvas.width, canvas.height);
// Two hills
drawHill(250, 300, 420, '#37c871', '#00a340');
drawHill(600, 330, 380, '#9be4b8', '#37c871');
}
function drawHill(x, top, radius, light, dark) {
let bottom = canvas.height;
let hill = context.createLinearGradient(0, top, 0, bottom);
hill.addColorStop(0, light);
hill.addColorStop(1, dark);
context.fillStyle = hill;
context.beginPath();
context.arc(x, top + radius, radius, 0, Math.PI * 2);
context.fill();
}
function loadPhoto(file) {
let photo = new Image();
photo.onload = function () {
// Fill the canvas, and cut off what doesn't fit
let scale = Math.max(
canvas.width / photo.width,
canvas.height / photo.height
);
let width = photo.width * scale;
let height = photo.height * scale;
let x = (canvas.width - width) / 2;
let y = (canvas.height - height) / 2;
// Start with white, for photos with transparency
context.fillStyle = 'white';
context.fillRect(0, 0, canvas.width, canvas.height);
context.drawImage(photo, x, y, width, height);
original = context.getImageData(
0, 0, canvas.width, canvas.height
);
URL.revokeObjectURL(photo.src);
dither();
};
photo.src = URL.createObjectURL(file);
}
function dither() {
// Start from a copy of the original pixels every time
let pixels = context.createImageData(
original.width, original.height
);
pixels.data.set(original.data);
if (method == 'gameBoy') {
ditherToGameBoy(pixels);
} else {
toGrayscale(pixels);
if (method == 'threshold') {
threshold(pixels, 128);
} else if (method == 'bayer') {
orderedDither(pixels, matrix);
} else if (method == 'floydSteinberg') {
diffuseError(pixels, floydSteinbergKernel, true);
} else if (method == 'atkinson') {
diffuseError(pixels, atkinsonKernel, true);
}
}
context.putImageData(pixels, 0, 0);
}
function toGrayscale(pixels) {
let data = pixels.data;
for (let i = 0; i < data.length; i += 4) {
let gray =
0.299 * data[i] +
0.587 * data[i + 1] +
0.114 * data[i + 2];
data[i] = gray;
data[i + 1] = gray;
data[i + 2] = gray;
}
}
function threshold(pixels, limit) {
let data = pixels.data;
for (let i = 0; i < data.length; i += 4) {
let value = data[i] < limit ? 0 : 255;
data[i] = value;
data[i + 1] = value;
data[i + 2] = value;
}
}
function orderedDither(pixels, matrix) {
let data = pixels.data;
let size = matrix.length;
for (let y = 0; y < pixels.height; y++) {
for (let x = 0; x < pixels.width; x++) {
let i = (y * pixels.width + x) * 4;
let cell = matrix[y % size][x % size];
let limit = (cell + 0.5) * 256 / (size * size);
let value = data[i] < limit ? 0 : 255;
data[i] = value;
data[i + 1] = value;
data[i + 2] = value;
}
}
}
function diffuseError(pixels, kernel, serpentine) {
let width = pixels.width;
let height = pixels.height;
let data = pixels.data;
let gray = new Float32Array(width * height);
for (let i = 0; i < gray.length; i++) {
gray[i] = data[i * 4];
}
function addError(x, y, amount) {
if (x >= 0 && x < width && y < height) {
gray[y * width + x] += amount;
}
}
for (let y = 0; y < height; y++) {
let direction = serpentine && y % 2 == 1 ? -1 : 1;
for (let step = 0; step < width; step++) {
let x = direction == 1 ? step : width - 1 - step;
let oldValue = gray[y * width + x];
let newValue = oldValue < 128 ? 0 : 255;
let error = oldValue - newValue;
gray[y * width + x] = newValue;
for (let spot of kernel) {
let spotX = x + spot.x * direction;
addError(spotX, y + spot.y, error * spot.weight);
}
}
}
for (let i = 0; i < gray.length; i++) {
data[i * 4] = gray[i];
data[i * 4 + 1] = gray[i];
data[i * 4 + 2] = gray[i];
}
}
function getClosestColor(red, green, blue, palette) {
let closest = palette[0];
let closestDistance = Infinity;
for (let color of palette) {
let dr = color[0] - red;
let dg = color[1] - green;
let db = color[2] - blue;
let distance = dr * dr + dg * dg + db * db;
if (distance < closestDistance) {
closestDistance = distance;
closest = color;
}
}
return closest;
}
function ditherToPalette(pixels, palette) {
let width = pixels.width;
let height = pixels.height;
let data = pixels.data;
let colors = new Float32Array(width * height * 3);
for (let i = 0; i < width * height; i++) {
colors[i * 3] = data[i * 4];
colors[i * 3 + 1] = data[i * 4 + 1];
colors[i * 3 + 2] = data[i * 4 + 2];
}
function addColorError(x, y, channel, amount) {
if (x >= 0 && x < width && y < height) {
colors[(y * width + x) * 3 + channel] += amount;
}
}
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
let i = (y * width + x) * 3;
let color = getClosestColor(
colors[i], colors[i + 1], colors[i + 2], palette
);
for (let channel = 0; channel < 3; channel++) {
let error = colors[i + channel] - color[channel];
colors[i + channel] = color[channel];
for (let spot of floydSteinbergKernel) {
addColorError(
x + spot.x, y + spot.y, channel,
error * spot.weight
);
}
}
}
}
for (let i = 0; i < width * height; i++) {
data[i * 4] = colors[i * 3];
data[i * 4 + 1] = colors[i * 3 + 1];
data[i * 4 + 2] = colors[i * 3 + 2];
}
}
function ditherToGameBoy(pixels) {
toGrayscale(pixels);
ditherToPalette(pixels, grays);
let data = pixels.data;
for (let i = 0; i < data.length; i += 4) {
let green = gameBoyPalette[data[i] / 85];
data[i] = green[0];
data[i + 1] = green[1];
data[i + 2] = green[2];
}
}
</script>
</body>
</html>Conclusion
Dithering lets you show shades that aren't there by making a pattern out of the colors you do have. A threshold throws the rounding error away. Random noise and the Bayer matrix hide it in grain or a regular pattern, and Floyd–Steinberg passes it on to the next pixels. With a palette, the same idea works in color, from the 16 colors of PICO-8 to the four greens of the Game Boy.
That's all for now. If you have any questions, feel free to ask them in the comment section. Made something cool with dithering? Tell us about it in the comments. Want to turn a photo into dots in another way? The tutorial about Voronoi diagrams shows how to make stipple art. You can download the example code here.
Comments
Thanks! We've received your comment. We check every comment by hand before it appears, so this can take a few days.

No comments yet. Be the first to leave one!