JSFiddle - React, Tailwind, and code Playground
HTML
<input type="text" id="text" value="S" /><button onclick="measure();">
Measure
</button>
<div class="preview">Please wait for preview fonts to be loaded</div>
<div id="result"></div>
<hr/><h3>CSV Data</h3>
<textarea style="width:100%" rows="5" cols="50" id="csv"></textarea>
CSS
@import url('https://fonts.googleapis.com/css?family=Dancing+Script|Indie+Flower|Metal+Mania|Nosifer|Pacifico|Ribeye+Marrow|Rye|Stalinist+One');
JavaScript
var fonts = [
'Stalinist One',
'Pacifico',
'Ribeye Marrow',
'Indie Flower',
'Rye',
'Nosifer',
'Dancing Script',
'Metal Mania'
];
//Create a preview sample for each font from the list
for(var i = 0; i < fonts.length; ++i) {
console.log("Creating preview for font: " + fonts[i]);
var res = $("<div style='font-family: \"" + fonts[i] + "\"'>This is a sample text</div>");
$(".preview").append(res);
}
//Using the sample from stackoverflow to calculate the measurements
/**
* Uses canvas.measureText to compute and return the width of the given text of given font in pixels.
*
* @param text The text to be rendered.
* @param {String} font The css font descriptor that text is to be rendered with (e.g. "14px verdana").
*
* @see http://stackoverflow.com/questions/118241/calculate-text-width-with-javascript/21015393#21015393
*/
function getTextWidth(text, font) {
// if given, use cached canvas for better performance
// else, create new canvas
var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
var context = canvas.getContext("2d");
context.font = font;
var metrics = context.measureText(text);
return metrics.width;
};
function getTextWidthDOM(text, font) {
var f = font || '12px arial',
o = $('<span>' + text + '</span>')
.css({'font': f, 'float': 'left', 'white-space': 'nowrap'})
.css({'visibility': 'hidden'})
.appendTo($('body')),
w = o.width();
return w;
}
//Measure the sample text
function measure() {
var header = "";
var row = "";
$(".preview").hide();
var text = $("#text").val();
$("#result").empty();
for(var i = 0; i < fonts.length; ++i) {
var current = $("<div></div>");
current.append($("<h4></h4>")
.text(fonts[i])
.css("font-family", fonts[i]));
var canvasWidth = getTextWidth(text, "normal normal 9.5pt " + fonts[i]);
var domWidth =...