Skip to content

Instantly share code, notes, and snippets.

@espretto
Last active October 9, 2020 08:01
Show Gist options
  • Save espretto/9527e62a6da2fc73b854a4c4beefbd49 to your computer and use it in GitHub Desktop.
Save espretto/9527e62a6da2fc73b854a4c4beefbd49 to your computer and use it in GitHub Desktop.
ts: measure text with offline canvas
const canvasContext = document
.createElement("canvas")
.getContext("2d") as CanvasRenderingContext2D;
/**
* measures text with the [canvas API](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/measureText)
* [avoiding expensive reflows](https://gist.github.com/Yukiniro/876826e1450b1f8cf755d2cea83cda65).
*/
export function measureText(text: string, font: string = "normal 16px serif") {
canvasContext.font = font;
return canvasContext.measureText(text);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment