I want to measure the theoretical width of some to-be-rendered text.
I like this method for getting text width, because it doesn't mutate the DOM
function getTextWidth(text, font) {
// re-use canvas object for better performance
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;
}
I have a CSS description of the font
.dx-widget {
color: #333;
font-weight: 400;
font-size: 14px;
font-family: "Helvetica Neue","Segoe UI",helvetica,verdana,sans-serif;
line-height: 1.35715;
}
How can I get in JavaScript the width that different strings would be according to these CSS rules?
I don't think I can apply this CSS class to the canvas to make it work.