Skip to content

Instantly share code, notes, and snippets.

@nkapliev
Last active February 16, 2017 06:35
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 nkapliev/c7fc221eac085219dfb9 to your computer and use it in GitHub Desktop.
Save nkapliev/c7fc221eac085219dfb9 to your computer and use it in GitHub Desktop.
How to compute chars width? 2 ways: DOM & Canvas
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
var getTextWidthDOM = function(text, fontStyle) {
var node = getTextWidthDOM.node,
width;
if ( ! node) {
node = getTextWidthDOM.node = document.createElement('span');
node.style.whiteSpace = 'nowrap';
node.style.visibility = 'hidden';
node.style.position = 'absolute';
node.style.height = 'auto';
node.style.width = 'auto';
}
document.body.appendChild(node);
node.style.font = fontStyle;
node.innerHTML = text;
width = node.offsetWidth;
document.body.removeChild(node);
return width;
};
var getTextWidthCanvas = function(text, fontStyle) {
getTextWidthCanvas.canvas || (getTextWidthCanvas.canvas = document.createElement("canvas"));
var context = getTextWidthCanvas.canvas.getContext("2d");
context.font = fontStyle;
return context.measureText(text).width;
};
var CHARS_RANGES = [
[ 0x0400, 0x04FF ], // Cyrillic
[ 0x001F, 0x007F ] // Latin
],
FONT_STYLE = '13px arial',
charsWidth = {};
CHARS_RANGES.forEach(function(range) {
for (var charCode = range[0], char; charCode <= range[1]; charCode++) {
char = String.fromCharCode(charCode);
charsWidth[char] = [
getTextWidthCanvas(char, FONT_STYLE),
getTextWidthDOM(char, FONT_STYLE)
];
}
});
console.log(charsWidth);
</script>
</body>
</html>
@nkapliev
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment