zoukankan      html  css  js  c++  java
  • canvas 文字换行

    引子

    近期的工作中,遇到的功能需求,需要控制文字显示行数,超过就省略号显示。

    文字换行

    一般文字行数控制用 css 就可以实现,但在 canvas 中不行。在网站查询资料,就可以发现需要程序控制文字换行,主要使用到的方法是 measureText(),这个方法会返回一个度量文本的相关信息的对象,例如文本的宽度。

    这里会有一个边界问题:如果文字在 canvas 边界出现换行,那么就可能出现文字显示不全的问题。

    主要处理方法如下:

    // 文本换行处理,并返回实际文字所占据的高度
    function textEllipsis (context, text, x, y, maxWidth, lineHeight, row) {
      if (typeof text != 'string' || typeof x != 'number' || typeof y != 'number') {
        return;
      }
      var canvas = context.canvas;
    
      if (typeof maxWidth == 'undefined') {
        maxWidth = canvas && canvas.width || 300;
      }
    
      if (typeof lineHeight == 'undefined') {
        // 有些情况取值结果是字符串,比如 normal。所以要判断一下
        var getLineHeight = window.getComputedStyle(canvas).lineHeight;
        var reg=/^[0-9]+.?[0-9]*$/;
        lineHeight = reg.test(getLineHeight)? getLineHeight:20;
      }
    
      // 字符分隔为数组
      var arrText = text.split('');
      // 文字最终占据的高度,放置在文字下面的内容排版,可能会根据这个来确定位置
      var textHeight = 0;
      // 每行显示的文字
      var showText = '';
      // 控制行数
      var limitRow = row;
      var rowCount = 0;
    
      for (var n = 0; n < arrText.length; n++) {
        var singleText = arrText[n];
        var connectShowText = showText + singleText;
        // 没有传控制的行数,那就一直换行
        var isLimitRow = limitRow ? rowCount === (limitRow - 1) : false;
        var measureText = isLimitRow ? (connectShowText+'……') : connectShowText;
        var metrics = context.measureText(measureText);
        var textWidth = metrics.width;
    
        if (textWidth > maxWidth && n > 0 && rowCount !== limitRow) {
          var canvasShowText = isLimitRow ? measureText:showText;
          context.fillText(canvasShowText, x, y);
          showText = singleText;
          y += lineHeight;
          textHeight += lineHeight;
          rowCount++;
          if (isLimitRow) {
            break;
          }
        } else {
          showText = connectShowText;
        }
      }
      if (rowCount !== limitRow) {
        context.fillText(showText, x, y);
      }
    
      var textHeightValue = rowCount < limitRow ? (textHeight + lineHeight): textHeight;
      return textHeightValue;
    }
    

    这是示例,扫描访问二维码如下。

    19-canvas-canvas-text

    参考资料

  • 相关阅读:
    常用的VI/VIM命令
    那些年学过的一些算法
    huffman编码
    好用java库(一):java date/time api:jodatime
    linux启动
    ubuntu学习方式
    地址
    各种各样的软件
    jquery文件
    C变量与数据
  • 原文地址:https://www.cnblogs.com/thyshare/p/13343226.html
Copyright © 2011-2022 走看看