h5 canvas自适应字体水平垂直居中

  • 实现思路:用二分法通过context.measureText测试文字宽高,不断计算字体大小
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<style>
  body {
    display: grid;
    place-items: center;
  }

  #demo-div {
    display: inline;
    background-color: skyblue;
    position: relative;
  }

  #demo-div::after {
    position: absolute;
    content: '';
    width: 0;
    height: 50px;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    border-left: 1px dashed red;
  }

  #demo-div::before {
    position: absolute;
    content: '';
    width: 200px;
    height: 0;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    border-top: 1px dashed purple;
  }

  .btn-list {
    display: flex;
    column-gap: 10px;
    margin-bottom: 20px;
  }
</style>

<body>

  <canvas id="demo-canvas" style="width: 400px; height: 200p;background-color: red;"></canvas>
  <div class="btn-list">
    <button id="times">Times</button>
    <button id="hanab">Hanab</button>
    <button id="magnetob">MAGNETOB</button>
    <button id="abc">abc</button>
    <button id="cn"></button>
    
  </div>
  <div id="demo-div">initial</div>
  <script>


    /**
     * @description: 生成预览图
     * @param {string} str 文本内容
     * @param {string} width 预览图宽度
     * @param {string} height 预览图高度
     * @param {number} initFontSize 初始字体尺寸
     * @param {string} initialTitle 字体名称
     */
    const generatePreview = async (
      str,
      width,
      height,
      font,
      fontUrl,
      initFontSize,
    ) => {
      try {

        // 处理高分屏
        const dpr = window.devicePixelRatio;
        // const canvas = document.createElement('canvas');
        const canvas = document.getElementById('demo-canvas');
        canvas.width = width * dpr;
        canvas.height = height * dpr;
        const ctx = canvas.getContext('2d')
        ctx.scale(dpr, dpr);

        // 绘制背景
        ctx.fillStyle = 'pink';
        ctx.fillRect(0, 0, 400, 200);
        ctx.fillStyle = 'black';

        ctx.font = `normal ${initFontSize}px Times New Roman`;
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';

        // 获取输入文本的实际高度
        const getActualHeight = () => {
          const { actualBoundingBoxAscent, actualBoundingBoxDescent } = ctx.measureText(str);
          return actualBoundingBoxAscent + actualBoundingBoxDescent;
        };

        // 获取输入文本的实际宽度
        const getActualWidth = () => {
          const { actualBoundingBoxLeft, actualBoundingBoxRight } = ctx.measureText(str);
          return actualBoundingBoxLeft + actualBoundingBoxRight;
        };

        /**
         * @description: 二分法计算合适的字体尺寸
         * @param {number} size 初始字体大小
         * @param {number} max 预览图最大宽 / 高
         * @param {function} culcalate 获取当前文本实际 宽 / 高 的计算函数
         */
        const dichotomizeCulcalate = (size, max, culcalate) => {
          let preResult;
          let minSize = size;
          let maxSize = size;
          do {
            preResult = culcalate();
            if (preResult > max) {
              maxSize = minSize;
              minSize = Math.floor(minSize / 2);
            } else {
              minSize = Math.floor((maxSize - minSize) / 2) + minSize;
            }
            // 判断完当前尺寸后更新文本信息,进入下一次循环
            ctx.font = `normal ${minSize}px ${font}`;
            if (maxSize === minSize) break;
          } while (preResult !== culcalate());
        };
        // 限制文字宽度
        dichotomizeCulcalate(initFontSize, width, getActualWidth);
        // 限制文字高度
        dichotomizeCulcalate(Number(ctx.font.split('px').shift()), height, getActualHeight);
        // 绘制文本
        ctx.fillText(
          str,
          (width - getActualWidth()) / 2 + ctx.measureText(str).actualBoundingBoxLeft, // 修正部分字体不由水平中线(center)均分导致的位移
          (height - getActualHeight()) / 2 + ctx.measureText(str).actualBoundingBoxAscent, // 修正部分字体不由垂直中线(middle)均分导致的位移
        );

        return new Promise((resolve, reject) => {
          canvas.toBlob((blob) => {
            if (blob) {
              resolve({
                previewBlobUrl: createObjectURL(blob), // 预览图本地链接
                previewBlob: blob,
              });
            } else {
              reject(new Error('预览图生成失败'));
            }
          });
        });
      } catch (error) {
        console.log(error)
      }
    };

    // 初始字体大小
    const INIT_FONTSIZE = 500;
    // 画布宽度(预览图宽度)
    const INIT_WIDTH = 400;
    // 画布宽度(预览图高度)
    const INIT_HEIGHT = 200;

    const div = document.getElementById('demo-div')
    document.getElementById('times').addEventListener('click', () => {
      generatePreview('Times', INIT_WIDTH, INIT_HEIGHT, 'Times', 'Times.ttc', INIT_FONTSIZE)
      div.innerText = 'Times'
      div.style.fontFamily = 'Times'
    })
    document.getElementById('hanab').addEventListener('click', () => {
      generatePreview('Hanab', INIT_WIDTH, INIT_HEIGHT, 'Hanab', 'Hanab.ttf', INIT_FONTSIZE)
      div.innerText = 'Hanab'
      div.style.fontFamily = 'Hanab'
    })
    document.getElementById('magnetob').addEventListener('click', () => {
      generatePreview('MAGNETOB', INIT_WIDTH, INIT_HEIGHT, 'MAGNETOB', 'MAGNETOB.ttf', INIT_FONTSIZE)
      div.innerText = 'MAGNETOB'
      div.style.fontFamily = 'MAGNETOB'
    })
    document.getElementById('abc').addEventListener('click', () => {
      generatePreview('abc', INIT_WIDTH, INIT_HEIGHT, 'MAGNETOB', 'MAGNETOB.ttf', INIT_FONTSIZE)
      div.innerText = 'abc'
    })
    document.getElementById('cn').addEventListener('click', () => {
      generatePreview('中', INIT_WIDTH, INIT_HEIGHT, 'MAGNETOB', 'MAGNETOB.ttf', INIT_FONTSIZE)
      div.innerText = '中'
    })
  </script>
</body>

</html>

你可能感兴趣的:(javascript,前端,css)