当前位置: 首页 > news >正文

vue3 计算字符串的高度与宽度,通过Canvas API的TextMetrics 接口来实现

1、先上一张官方的说明图:

地址:https://developer.mozilla.org/zh-CN/docs/Web/API/TextMetrics

官方实例:

<canvas id="canvas" width="550" height="500"></canvas>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const baselinesAboveAlphabetic = ["fontBoundingBoxAscent","actualBoundingBoxAscent","emHeightAscent","hangingBaseline",
];
const baselinesBelowAlphabetic = ["ideographicBaseline","emHeightDescent","actualBoundingBoxDescent","fontBoundingBoxDescent",
];
const baselines = [...baselinesAboveAlphabetic, ...baselinesBelowAlphabetic];
ctx.font = "25px serif";
ctx.strokeStyle = "red";
baselines.forEach((baseline, index) => {const text = `Abcdefghijklmnop (${baseline})`;const textMetrics = ctx.measureText(text);const y = 50 + index * 50;ctx.beginPath();ctx.fillText(text, 0, y);let lineY = y - Math.abs(textMetrics[baseline]);if (baselinesBelowAlphabetic.includes(baseline)) {lineY = y + Math.abs(textMetrics[baseline]);}ctx.moveTo(0, lineY);ctx.lineTo(550, lineY);ctx.stroke();
});

运行效果说明:

2、然后我们用vue3做一个小的demo测试下(以下代码修改于baidu ai):

<template><div><canvas ref="canvas" style="display: none;"></canvas><p>Text height: {{ textHeight }}px</p></div></template><script setup>import { ref, onMounted, watch } from 'vue';const text = ref('您好世界');const textHeight = ref(0);const canvas = ref(null);onMounted(() => {measureTextHeight();});watch(text, measureTextHeight);function measureTextHeight() {const ctx = canvas.value.getContext('2d');ctx.font = '20px Microsoft Yahei';const metrics = ctx.measureText(text.value);let width = metrics.width;let height = metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent;textHeight.value = height;return { width, height };}</script>

运行结果:

说明:这种方法canvas可以精确的计算出,当然也有通过动态创建div,然后通过div的高度来计算,此方法测试发现不是很精确。当然实际开发过程中要进行适当调整。

代码也帖出来:

 function getWordHeight(fontSize: string, fontFamily: string, sTextStr: string) {console.log('getWordHeight:', sTextStr);let newDiv = document.createElement('div');newDiv.style.fontSize = fontSize + 'px';newDiv.style.fontFamily = fontFamily;newDiv.innerText = sTextStr;// 将新 div 插入文档流中,这样才能计算出其高度和宽度document.body.appendChild(newDiv);// 计算新 div 的高度和宽度let height = newDiv.offsetHeight; //clientHeightlet width = newDiv.offsetWidth; //clientWidth// 从文档流中移除新 divnewDiv.remove();return { width, height };}


http://www.mrgr.cn/news/50571.html

相关文章:

  • 初识Java: 常见注意事项总结
  • 从零创建苹果App应用,不知道怎么申请证书的可以先去看我的上一篇文章
  • .net core 3.0 与 6.0 有哪些不同
  • web 0基础第六节 表格标签
  • springboot 拷贝了一个module 启不起来
  • kubernetes--资源调度Selector/Deployment/SatatefulSet/DaemonSet
  • 【java】— 类和对象(这一篇就够了)
  • Podman 的一些常用指令
  • 【Next.js 项目实战系列】01-创建项目
  • 匿名管道和命名管道
  • 想高薪!普通人转行做AI,试试这5步!
  • 胤娲科技:Pika 1.5燃爆登场——AI视频特效,让万物“笑”果全开
  • 初级网络工程师之从入门到入狱(四)
  • 每月洞察:App Store 和 Google Play 的主要更新
  • 什么台灯护眼效果好?五款专业护眼灯款式分享
  • RHCSA复习题
  • WebServer构建响应 发送响应
  • 如何解决数字化转型的老大难,突破部门流程墙
  • 歌曲怎么去掉原唱只留伴奏?创作无界,轻松获取伴奏音轨
  • 第1章:Flux学习前言(必读)