马黑PHP整站系统

1234567
891011121314
15161718192021
22232425262728
2930     

[复位日记]

最新评论

悄然
飞飞
马黑
悄然
飞飞

网站统计

·今日访问 : 94
·页面点击 : 99
·当前在线 : 9

2025年6月18日 星期三[阅读 7]

通过离线canvas获取一行文本的宽高数据:

  1. function getTxtSize(txt, font) {
  2.     const c = document.createElement('canvas');
  3.     const ct = c.getContext('2d');
  4.     ct.font = font;
  5.     const metrics = ct.measureText(str);
  6.     const width = metrics.width;
  7.     const height = metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent;
  8.     return { width: width, height: height };
  9. };
参数:
  1. txt : 要输出的文本
  2. font : 字体设置,例如 : 'bold 80px sans-serif'

返回的width和height很抠,实实在在的文本宽高,实际使用时应加值留边。

2025': 前一则  下一则    

发表评论:

       

Copyright © 2023 All Right Reserved 马黑PHP文章管理整站系统v1.8
联系我们: gxblk@163.com