JSFiddle - React, Tailwind, and code Playground
by Andrew Poes
HTML
<canvas width="36" height="22"></canvas>
<a id="download" download="atlas.jpg" href="" onclick="download_img(this);">Download texture atlas</a>
CSS
canvas {
outline: 1px solid #000000;
}
JavaScript
/* let string = "1234567890-=!@#$%^&&*()_+qwertyuiop[]asdfghjkl;'zxcvbnm,./QWERTYUIOP{}ASDFGHJKL:ZXCVBNM<>?¡™£¢∞§¶•ªº–≠œ∑´®†¥¨ˆ“‘åßlet©˙∆˚¬…æΩ≈˜µ÷ç√"; */
let string = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100";
/* string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; */
let chars = string.split(",");
let font = "10px Helvetica Neue";
download_img = function(el) {
// get image URI from canvas object
var imageURI = canvas.toDataURL("image/jpg");
el.href = imageURI;
};
function getRndColor() {
var r = 255*Math.random()|0,
g = 255*Math.random()|0,
b = 255*Math.random()|0;
return 'rgb(' + r + ',' + g + ',' + b + ')';
}
var gridX = Math.ceil(Math.sqrt(chars.length));
var gridY = Math.ceil(chars.length / gridX);
// Configure the sheet.
const canvas = document.querySelector("canvas");
const charWidth = canvas.width;
const charHeight = canvas.height;
canvas.width = gridX * charWidth;
canvas.height = gridY * charHeight;
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.rect(0, 0, gridX * charWidth, gridY *charHeight);
ctx.fillStyle = "white";
ctx.fill();
ctx.fillStyle = "black";
ctx.font = font;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
var charIndex = 0;
for (let y = 0; y < gridY; ++y) {
for (let x = 0; x < gridX; ++x) {
if (charIndex < chars.length) {
const char = chars[charIndex++];
const posX = x * charWidth + charWidth / 2;
const posY = y * charHeight + charHeight / 2;
//ctx.fillStyle = getRndColor();
ctx.fillStyle = "white";
ctx.fillRect(posX - charWidth / 2, posY - charHeight / 2, charWidth, charHeight);
//ctx.fillStyle = getRndColor();
ctx.fillStyle = "#222";
ctx.fillText(char, posX, posY);
}
}
}
console.log('t=', chars.length, '...