Skip to content
← Work log

Canvas can't read oklch tokens

The topographic background draws to a canvas, and the original pulled its colours by regexing digits out of getComputedStyle().color and passing the custom properties through raw. That works with hex tokens. Ours are oklch() wrapped in light-dark(var(…)), so the regex found nothing useful and canvas got handed a var() it can't read.

The fix is to let the browser do the resolving. Set the expression as the colour of a hidden span, read the computed value back, and for the plain r,g,b triplet paint it onto a 1×1 canvas and read the pixel.

ts008 LN
1function toRgbTriplet(cssColor: string): string {
2 const probe = document.createElement("canvas").getContext("2d", { willReadFrequently: true })
3 if (!probe) return "242,242,240"
4 probe.fillStyle = cssColor
5 probe.fillRect(0, 0, 1, 1)
6 const [red, green, blue] = probe.getImageData(0, 0, 1, 1).data
7 return `${red},${green},${blue}`
8}

Slightly daft, but it handles any colour syntax the browser does, which is the point.

canvascsscolour
AI-OMETER— DISCLOSURE INDEX
CO-WRITTEN70%