Skip to content

Drawing to a Canvas ​

The helpers in hazehash/canvas decode a hash and put the result into a canvas. They need ImageData, so they run in a browser, in a worker with OffscreenCanvas, or in any environment that provides it. The module adds about 0.05 KB gzip on top of the decoder.

ts
import { drawToCanvas, toImageData } from 'hazehash/canvas'

Drawing a placeholder ​

drawToCanvas(hash, canvas, options?)

Decodes the hash and paints it into the canvas, resizing the canvas to the decoded size first. The canvas then has the pixel size of the preview (32×25 for the default size and a 13:10 hash), so stretch it with CSS to the size of the image box. Nothing is returned.

ts
import { drawToCanvas } from 'hazehash/canvas'

drawToCanvas(hash, document.querySelector('canvas') as HTMLCanvasElement)
css
.frame {
  position: relative;
  overflow: hidden;
}

.frame canvas {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
}

hash ​

string | Uint8Array

The hash to draw.

canvas ​

CanvasLike

An HTMLCanvasElement or an OffscreenCanvas. The type is the small surface both share:

ts
interface CanvasLike {
  width: number
  height: number
  getContext(type: '2d'): { putImageData(data: ImageData, x: number, y: number): void } | null
}

If getContext('2d') returns null, the canvas is resized and left empty.

options ​

DecodeOptions · optional

The same size and dither as in decode().

Getting an ImageData ​

toImageData(hash, options?)

ImageData

Decodes the hash into an ImageData object without touching a canvas, for when you draw it yourself: with createImageBitmap(), into a canvas you manage, or into a WebGL texture. The pixel buffer is a copy that ImageData accepts.

ts
import { toImageData } from 'hazehash/canvas'

const image = toImageData(hash, { size: 64 })
context.putImageData(image, 0, 0)

Before the script runs ​

A canvas is drawn only when JavaScript runs, so give the box its colour and shape from the header first. This is cheap and works on the server too:

ts
import { getAspectRatio, getAverageColor } from 'hazehash'

const { r, g, b } = getAverageColor(hash)
frame.style.backgroundColor = `rgb(${r}, ${g}, ${b})`
frame.style.aspectRatio = String(getAspectRatio(hash))

In Vue, <PlaceholderImage> does exactly this and draws the canvas after mount.