Created
May 31, 2022 02:37
-
-
Save yuzhouu/184b1179bf7802aec5f24391e2c837fb to your computer and use it in GitHub Desktop.
convert text to text-image
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
interface Options { | |
fontFamily?: string; | |
fontSize?: number; | |
} | |
export default function text2image(text: string, opts?: Options) { | |
const { fontFamily = "serif", fontSize = 14 } = opts || {}; | |
// high ratio, high dpi | |
const ratio = Math.max(window.devicePixelRatio || 4, 4); | |
const canvas = document.createElement("canvas"); | |
const context = canvas.getContext("2d")!; | |
context.scale(ratio, ratio); | |
context.font = `${fontSize}px ${fontFamily}`; | |
context.fillStyle = "#000"; | |
const textMetrics = context.measureText(text); | |
// | |
canvas.style.width = `${textMetrics.width}px`; | |
canvas.style.height = `${textMetrics.fontBoundingBoxAscent}px`; | |
canvas.width = textMetrics.width * ratio; | |
canvas.height = textMetrics.fontBoundingBoxAscent * ratio; | |
context.scale(ratio, ratio); | |
context.font = `${fontSize}px ${fontFamily}`; | |
context.fillStyle = "#000"; | |
context.fillText( | |
text, | |
0, | |
textMetrics.fontBoundingBoxAscent - textMetrics.actualBoundingBoxDescent | |
); | |
return canvas.toDataURL("image/png", 1.0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment