Last active
November 5, 2021 19:42
-
-
Save Sheraff/69b4467ef3e5f188d7f91909b29fed10 to your computer and use it in GitHub Desktop.
styled text on canvas
This file contains hidden or 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
{ | |
"scripts": [], | |
"styles": [] | |
} |
This file contains hidden or 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
<canvas width="500" height="500"></canvas> |
This file contains hidden or 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 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}` | |
} |
This file contains hidden or 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
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