Skip to content

Instantly share code, notes, and snippets.

@Sheraff
Last active November 5, 2021 19:42
Show Gist options
  • Save Sheraff/69b4467ef3e5f188d7f91909b29fed10 to your computer and use it in GitHub Desktop.
Save Sheraff/69b4467ef3e5f188d7f91909b29fed10 to your computer and use it in GitHub Desktop.
styled text on canvas
{
"scripts": [],
"styles": []
}
<canvas width="500" height="500"></canvas>
const text = "Lorem Ipsum is … typesetting industry."
const style = `
margin: 0;
font-weight: normal;
font-family: serif;
font-size: 20px;
line-height: 32px;
color: white;
`
const width = 200
const height = 100
const context = document.querySelector("canvas").getContext("2d")
drawTextOnCanvas(context, text, 0, 0, width, height, style)
function drawTextOnCanvas(context, text, x, y, width, height, style) {
const svgTemplate = (text, style, width, height) => `
<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
<foreignObject x="0" y="0" width="${width}" height="${height}">
<style>
p {
${style}
}
</style>
<p xmlns="http://www.w3.org/1999/xhtml">
${text}
</p>
</foreignObject>
</svg>`
// Get the SVG code in string format <svg>...
const svgCode = svgTemplate(text, style, width, height)
// Remove newlines and replace double quotes with single quotes
const svgCodeEncoded = svgCode.replace(/\n/g, "").replace(/"/g, "'")
// Dynamically create an image element
const img = document.createElement("img")
// Wait for the image to load before drawing it to the canvas
img.onload = () => context.drawImage(img, x, y, width * 2, height * 2)
// Load our SVG to the image
img.src = `data:image/svg+xml,${svgCodeEncoded}`
}
canvas {
transform: scale(0.5);
transform-origin: 0 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment