Get Character Intensity
Get the intensity of different characters for use in automated ASCII art.
by Santiago J
HTML
<div id="output"></div>
CSS
body {
background-color: #000;
color: #fff;
margin: 0;
padding: 0;
}
JavaScript
function getAvgIntensity(ctx, x, y, w, h) {
var d = ctx.getImageData(x,y,w,h).data, n = d.length, s = 0, i;
for (i=0; i<n; i+=4) s += d[i] + d[i+1] + d[i+2];
return s;
}
function fontIntensityPlot(intensities, font, w, h) {
var cnv = document.createElement("canvas"),
ctx = cnv.getContext("2d"),
maxInt = 0, n = 0, i;
cnv.title = font;
cnv.width = w;
cnv.height = h;
for (i in intensities) {
if (intensities[i] > maxInt) maxInt = intensities[i];
n++;
}
ctx.font = font;
ctx.fillStyle = "#fff";
var x = 0;
for (i in intensities) {
ctx.fillText(i, x, intensities[i]*h/maxInt);
x += w/n;
}
return cnv;
}
function getFontIntensity(font, W, H, plot) {
var ctx = document.createElement("canvas").getContext("2d"),
chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ !@#$%^&*()-=+`~[]\\;',./{}|:\"<>?\u2591\u2592\u2593\u2588",
intensities = {};
// Set up us the canvas
ctx.canvas.width = W;
ctx.canvas.height = H;
ctx.font = font;
ctx.textBaseline = "top";
// Test characters
var len = chars.length, i, ch;
for (i=0; i<len; i++) {
ch = chars.charAt(i);
ctx.fillStyle = "#000";
ctx.fillRect(0,0,W,H);
ctx.fillStyle = "#fff";
ctx.fillText(ch,0,0);
intensities[ch] = getAvgIntensity(ctx,0,0,W,H);
}
// plot them?
if (plot) document.body.appendChild(fontIntensityPlot(intensities, font, 800, 600));
// Sort them in a string and return the string
var orderedChars = [];
for (i in intensities) orderedChars.push(i);
orderedChars.sort(function(a,b){ return intensities[a] - intensities[b]; });
return orderedChars.join("");
}
window.onload = function(){
var log = document.getElementById("output");
function logFontIntensity(font, w, h, alsoPlot) {
var out = document.createElement("div");
out.style.font = font;
...