Skip to content

Instantly share code, notes, and snippets.

@jbenner-radham
Last active June 4, 2025 17:37
Show Gist options
  • Save jbenner-radham/79f61c7a04615539253a2d0e7a2a9dd4 to your computer and use it in GitHub Desktop.
Save jbenner-radham/79f61c7a04615539253a2d0e7a2a9dd4 to your computer and use it in GitHub Desktop.
JS/TS Snippets
const get2dCanvasContext = (): CanvasRenderingContext2D | null => {
const canvas = document.createElement('canvas')
const context = canvas.getContext('2d')
if (!context) return context
const { fontWeight, fontSize, fontFamily } = window.getComputedStyle(document.body)
context.font = `${fontWeight} ${fontSize} ${fontFamily}`
return context
}
const context = get2dCanvasContext()
if (!context) {
// Handle null context...
}
const textWidth = context.measureText('Hello world!').width
const pxPerRem = Number.parseFloat(window.getComputedStyle(document.documentElement).fontSize)
const sleep = (milliseconds: number = 0): Promise<void> => new Promise(resolve => setTimeout(resolve, milliseconds));
console.log('I feel asleep...');
await sleep(1_000);
console.log('Wakey wakey!');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment