Last active
February 16, 2017 06:35
-
-
Save nkapliev/c7fc221eac085219dfb9 to your computer and use it in GitHub Desktop.
How to compute chars width? 2 ways: DOM & Canvas
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://developer.mozilla.org/en-US/docs/Web/API/TextMetrics