Dither Effect in CSS: A Pure CSS Method and a Canvas Method | HorizonX
← The Journal

CSS

Dither Effect in CSS: A Pure CSS Method and a Canvas Method

Build a dither effect on an image with CSS only, or with a short canvas script. Both methods tested, with the Bayer threshold map explained.

Marcelo Cedeño

Marcelo Cedeño

·6 min read

Dither Effect in CSS: A Pure CSS Method and a Canvas Method
  • Meta description: Build a dither effect on an image with CSS only, or with a short canvas script. Both methods tested, with the Bayer threshold map explained.
  • Slug: dither-effect-css
  • Target query: dither effect css

A dither effect turns a smooth image into a pattern of two colours by comparing each pixel with a repeating map of thresholds. You can do that in the browser in two ways: a CSS-only method that needs no JavaScript, and a canvas method that gives you full control of the colours. Both are below, with the code I tested.

If you are still deciding between dithering, halftone and ASCII for a project, start with Dithering vs Halftone vs ASCII. This guide is the code side.

How ordered dithering works#

Ordered dithering uses a small matrix of thresholds that repeats across the image. A pixel becomes the light colour if it is brighter than the threshold under it, and the dark colour if not. Dark areas end up with sparse light dots and bright areas with sparse dark ones, which is where the pattern comes from.

The classic 4x4 Bayer matrix is:

 0   8   2  10
12   4  14   6
 3  11   1   9
15   7  13   5

Divide each value (plus one half) by 16 to get a threshold between 0 and 1. Wikipedia's ordered dithering article describes the same matrix and the comparison rule.

Method 1: CSS only#

CSS cannot compare two layers directly, but blending and filters can imitate the comparison:

  1. Halve the photo's brightness, so every value sits between 0 and 0.5.
  2. Add a tiled threshold map on top with mix-blend-mode: plus-lighter. Each tile cell is set to half of one minus its threshold.
  3. The sum passes 0.5 exactly where the photo is brighter than the threshold. A very strong contrast() on the wrapper then snaps every pixel to black or white around 0.5.

The threshold map is a 4 by 4 pixel SVG file. Save it as bayer4.svg:

<svg xmlns="http://www.w3.org/2000/svg" width="4" height="4" shape-rendering="crispEdges">
  <rect x="0" y="0" width="1" height="1" fill="#7c7c7c"/>
  <rect x="1" y="0" width="1" height="1" fill="#3c3c3c"/>
  <rect x="2" y="0" width="1" height="1" fill="#6c6c6c"/>
  <rect x="3" y="0" width="1" height="1" fill="#2c2c2c"/>
  <rect x="0" y="1" width="1" height="1" fill="#1c1c1c"/>
  <rect x="1" y="1" width="1" height="1" fill="#5c5c5c"/>
  <rect x="2" y="1" width="1" height="1" fill="#0c0c0c"/>
  <rect x="3" y="1" width="1" height="1" fill="#4c4c4c"/>
  <rect x="0" y="2" width="1" height="1" fill="#646464"/>
  <rect x="1" y="2" width="1" height="1" fill="#242424"/>
  <rect x="2" y="2" width="1" height="1" fill="#747474"/>
  <rect x="3" y="2" width="1" height="1" fill="#343434"/>
  <rect x="0" y="3" width="1" height="1" fill="#040404"/>
  <rect x="1" y="3" width="1" height="1" fill="#444444"/>
  <rect x="2" y="3" width="1" height="1" fill="#141414"/>
  <rect x="3" y="3" width="1" height="1" fill="#545454"/>
</svg>

Then the HTML and CSS:

<div class="dither">
  <img src="photo.jpg" alt="Describe the photo here">
</div>
@supports (mix-blend-mode: plus-lighter) {
  .dither {
    --cell: 2px;                          /* size of one dither pixel */
    position: relative;
    isolation: isolate;
    filter: contrast(1000);               /* hard threshold at 50% */
  }
  .dither img {
    display: block;
    width: 100%;
    filter: grayscale(1) brightness(0.5); /* photo halved: values 0 to 0.5 */
  }
  .dither::after {
    content: "";
    position: absolute;
    inset: 0;
    mix-blend-mode: plus-lighter;         /* photo + threshold map */
    image-rendering: pixelated;
    background: url("bayer4.svg") 0 0 / calc(var(--cell) * 4) calc(var(--cell) * 4);
  }
}

Change --cell to make the pattern coarser or finer. The @supports wrapper means a browser without plus-lighter shows the plain photo instead of a broken effect.

The result is black and white only, and the threshold is applied to the colour values as the browser stores them, not to linear light. Expect it to look a little different from dither tools that work in linear light.

Method 2: canvas#

When you want your own two colours, or a lower resolution that matches the dither pixel, use a canvas. This function draws the image at 1 / cell of its size, applies the same Bayer matrix and returns a canvas.

const BAYER4 = [
  [ 0,  8,  2, 10],
  [12,  4, 14,  6],
  [ 3, 11,  1,  9],
  [15,  7, 13,  5],
];

function ditherImage(img, { cell = 2, ink = [17, 24, 39], paper = [250, 247, 240] } = {}) {
  const w = Math.floor(img.naturalWidth / cell);
  const h = Math.floor(img.naturalHeight / cell);
  const canvas = document.createElement('canvas');
  canvas.width = w;
  canvas.height = h;
  const ctx = canvas.getContext('2d', { willReadFrequently: true });
  ctx.drawImage(img, 0, 0, w, h);

  const frame = ctx.getImageData(0, 0, w, h);
  const px = frame.data;
  for (let y = 0; y < h; y++) {
    for (let x = 0; x < w; x++) {
      const i = (y * w + x) * 4;
      const lum = (0.2126 * px[i] + 0.7152 * px[i + 1] + 0.0722 * px[i + 2]) / 255;
      const threshold = (BAYER4[y % 4][x % 4] + 0.5) / 16;
      const c = lum > threshold ? paper : ink;
      px[i] = c[0]; px[i + 1] = c[1]; px[i + 2] = c[2]; px[i + 3] = 255;
    }
  }
  ctx.putImageData(frame, 0, 0);
  return canvas;
}

Use it once the image has loaded, and scale the canvas up with image-rendering: pixelated so the dots stay sharp:

const img = new Image();
img.onload = () => {
  const canvas = ditherImage(img, { cell: 2 });
  canvas.style.cssText = 'width:320px;height:320px;image-rendering:pixelated';
  document.body.append(canvas);
};
img.src = 'photo.png';

The image must come from the same origin, or from a server that sends CORS headers. Otherwise the browser blocks getImageData.

Which method to use#

  • Pure CSS: no script, the image stays a normal img, and you control the dot size with one variable. It is black and white and relies on a newer blend mode.
  • Canvas: any two colours, exact pixel output and a result you can save as an image. It needs JavaScript and a same-origin or CORS-enabled image.
  • A pre-rendered image: if the picture does not change, export the dithered file once and serve it as a normal image. No runtime cost and the same look in every browser.

When you would rather not write the code#

HorizonX has dither editors for the pre-rendered route. Image Dithering Effect is the main image dithering editor: load your picture, tune the dither pixel size and gamma, and switch between patterns. Bit Plate reduces an image to one bit with an 8x8 Bayer screen, and its dither style menu also offers Bayer 2x2 and 4x4, a 1-bit threshold, halftone circle, film grain and stardust. Both let you set the foreground and background colours and export a PNG. See every look in the Dither Effects collection, or browse all image effect editors.

How these snippets were checked#

I ran both methods in Chromium on a generated 320 by 320 test image. The canvas output contained exactly two colours. In a screenshot of the CSS-only output every pixel was either black or white (102,400 pixels, two values). A smaller contrast() factor, such as 40, left a few percent of grey pixels, which is why the snippet uses 1000. Safari and Firefox were not tested; check the CSS method there before relying on it.

Next step#

Try the pattern on your own image: Open Image Dithering Effect and dither a picture.