Font metrics
by Adam Granger
HTML
<div id="foo">
<input class="bar" type="text" placeholder="measure text" />
</div>
<canvas id="debug">
</canvas>
CSS
#debug {
width: 300px;
height: 300px;
}
@font-face {
font-family: 'Transport';
src: url('http://adamg-devpc/transportmedium/TransportMedium.ttf');
}
#foo .bar {
font-family: "Transport";
font-size: 30pt;
}
JavaScript
function measure(str) {
var c=$("<canvas></canvas>")[0];
var ctx=c.getContext("2d");
ctx.font="30pt Transport";
return ctx.measureText(str).width;
}
function update(w) {
var c = $("#debug")[0];
var context = c.getContext("2d");
context.clearRect(0, 0, $(c).width(), $(c).height());
context.fillRect(0, 0, w, 50);
}
console.log("test");
$("#foo .bar").keyup(function() {
var text = $("#foo .bar").val();
var size = measure(text);
console.log("foo " + text + " " + size + "px");
update(size);
});