Last active
October 9, 2020 08:01
-
-
Save espretto/9527e62a6da2fc73b854a4c4beefbd49 to your computer and use it in GitHub Desktop.
ts: measure text with offline canvas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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