Skip to content

Instantly share code, notes, and snippets.

@PavelLaptev
Created September 11, 2020 13:31
Show Gist options
  • Save PavelLaptev/a49c6f2244e445c8d4d1467567a29f4f to your computer and use it in GitHub Desktop.
Save PavelLaptev/a49c6f2244e445c8d4d1467567a29f4f to your computer and use it in GitHub Desktop.
generateTexture.js
export const generateTexture = (text) => {
// Set variables
const bitmapShift = 80;
const copyAmount = 4;
const canvasSize = 300;
const fontSize = canvasSize / copyAmount;
const fontStyle = `Bold ${fontSize}px Arial`;
// Create canvas
const bitmap = document.createElement("canvas");
bitmap.height = canvasSize;
// Create 2d context
const g = bitmap.getContext("2d");
g.font = fontStyle;
bitmap.width = g.measureText(text).width;
// Add font style again
g.fillStyle = "blue";
g.font = fontStyle;
// Add text on the canvas
const scaledText = (index) =>
g.fillText(text, 0, fontSize * ++index - bitmapShift);
Array(copyAmount + 1)
.fill(0)
.forEach((item, i) => {
scaledText(i);
});
const background = bitmap.toDataURL("image/png");
return background;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment