Skip to content

Instantly share code, notes, and snippets.

@qoh
Created March 9, 2016 16:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qoh/2acc736a7574c781259e to your computer and use it in GitHub Desktop.
Save qoh/2acc736a7574c781259e to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
#canvas {
background-color: black;
}
</style>
</head>
<body>
<p>
<input type="text" id="family" value="monospace">
<input type="text" id="shape" value="[512, 512]">
<input type="text" id="step" value="[32, 32]">
<input type="text" id="size" value="16px">
<input type="text" id="chars" value="[32, 126]">
<button id="paint">Paint atlas</button>
</p>
<canvas id="canvas" width="512" height="512"></canvas>
<script>
(function() {
var defaultChars = [32, 126]
window.fontAtlas = atlas
function atlas(options) {
options = options || {}
var canvas = options.canvas || document.createElement('canvas')
var family = options.family || 'monospace'
var shape = options.shape || [512, 512]
var step = options.step || [32, 32]
var size = options.size || 16
var chars = options.chars || defaultChars
if (typeof size === 'number') {
size = size + 'px'
}
if (!Array.isArray(chars)) {
chars = String(chars).split('')
} else
if (chars.length === 2
&& typeof chars[0] === 'number'
&& typeof chars[1] === 'number'
) {
var newchars = []
for (var i = chars[0], j = 0; i <= chars[1]; i++) {
newchars[j++] = String.fromCharCode(i)
}
chars = newchars
}
shape = shape.slice()
canvas.width = shape[0]
canvas.height = shape[1]
var ctx = canvas.getContext('2d')
// ctx.fillStyle = '#000'
// ctx.fillRect(0, 0, canvas.width, canvas.height)
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.font = size + ' ' + family
ctx.textAlign = 'center'
ctx.textBaseline = 'middle'
ctx.fillStyle = '#fff'
var x = step[0] / 2
var y = step[1] / 2
for (var i = 0; i < chars.length; i++) {
ctx.fillText(chars[i], x, y)
if ((x += step[0]) > shape[0] - step[0]/2) (x = step[0]/2), (y += step[1])
}
return canvas
}
})();
</script>
<script>
document.getElementById("paint").addEventListener("click", function() {
fontAtlas({
canvas: document.getElementById("canvas"),
family: document.getElementById("family").value,
shape: JSON.parse(document.getElementById("shape").value),
step: JSON.parse(document.getElementById("step").value),
size: document.getElementById("size").value,
chars: JSON.parse(document.getElementById("chars").value),
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment