Skip to content

Instantly share code, notes, and snippets.

@eightHundreds
Created November 27, 2020 01:55
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 eightHundreds/0fa7234fabe7697906436263d6ee43fa to your computer and use it in GitHub Desktop.
Save eightHundreds/0fa7234fabe7697906436263d6ee43fa to your computer and use it in GitHub Desktop.
计算文本宽度
/**
* 计算文本长度
* @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