Created
November 27, 2020 01:55
-
-
Save eightHundreds/0fa7234fabe7697906436263d6ee43fa to your computer and use it in GitHub Desktop.
计算文本宽度
This file contains 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
/** | |
* 计算文本长度 | |
* @param text | |
* @see https://stackoverflow.com/questions/118241/calculate-text-width-with-javascript | |
*/ | |
function getTextWidth(text: string) { | |
// @ts-ignore | |
const canvas: HTMLCanvasElement = getTextWidth.canvas || (getTextWidth.canvas = document.createElement('canvas')); | |
const context = canvas.getContext('2d'); | |
context!.font = '14px sans-serif'; // 14px是猜测的,不能确定 | |
const metrics = context!.measureText(text); | |
return metrics.width; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment