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; //clientHeight
    let width = newDiv.offsetWidth; //clientWidth

   
    // 从文档流中移除新 div
    newDiv.remove();
    return { width, height };
  }

猜你喜欢

转载自blog.csdn.net/jwbabc/article/details/142938011