Created
February 2, 2018 03:04
-
-
Save YingshanDeng/26da244b567674f50b47791312849c38 to your computer and use it in GitHub Desktop.
字体测量
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
function fontMetrics (family, size) { | |
this._family = family || (family = "Monaco, 'Courier New', Courier, monospace") | |
this._size = parseInt(size, 10) || (size = 12) | |
// Preparing container | |
var line = document.createElement('div') | |
var body = document.body | |
line.style.position = 'absolute' | |
line.style.whiteSpace = 'nowrap' | |
line.style.font = size + 'px ' + family | |
body.appendChild(line) | |
// Now we can measure width and height of the letter | |
var text = 'mmmmmmmmmm' // 10 symbols to be more accurate with width | |
line.innerHTML = text | |
this._width = line.offsetWidth / text.length | |
this._height = line.offsetHeight | |
// Now creating 1px sized item that will be aligned to baseline | |
// to calculate baseline shift | |
var span = document.createElement('span') | |
span.style.display = 'inline-block' | |
span.style.overflow = 'hidden' | |
span.style.width = '1px' | |
span.style.height = '1px' | |
line.appendChild(span) | |
// Baseline is important for positioning text on canvas | |
this._baseline = span.offsetTop + span.offsetHeight | |
document.body.removeChild(line) | |
return { | |
family: this._family, | |
size: this._size, | |
width: this._width, | |
height: this._height, | |
baseline: this._baseline | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment