d3 text自动换行

看了一篇挺好的文章:https://www.zhangshengrong.com/p/24Njld01B7/

在此换行的基础上添加了超长省略的功能。
先看一下自动换行的部分

/**
 * 自动换行
 * @param str 
 * @param width
 * @param fontsize
 * @param line 显示的行数
 */
function splitByLine(
  str: string,
  width: number,
  fontsize: number,
  line?: number
) {
  let curLen = 0
  let result = []
  let start = 0
  let end = 0

  for (let i = 0; i < str.length; i++) {
    let code = str.charCodeAt(i)
    let pixelLen = code > 255 ? fontsize : fontsize / 2
    curLen += pixelLen
    if (curLen > width) {
      end = i
      result.push(str.substring(start, end))

      start = i
      curLen = pixelLen
    }
    if (i === str.length - 1) {
      end = i
      result.push(str.substring(start, end + 1))
    }
  }
  return line ? result.slice(0, line) : result
}

在上诉基础上,加了一个超长省略功能,若超出指定行数,则使用...

/**
 * text 超长省略(多行省略)
 * @param str
 * @param width
 * @param fontsize
 * @param line 行数
 */
function textEllipsis(
  str: string,
  width: number,
  fontsize: number,
  line: number = 1
) {
  let curLen = 0
  let result = []
  let start = 0
  let end = 0

  for (let i = 0; i < str.length; i++) {
    if (result.length === line) {
      break
    }

    let code = str.charCodeAt(i)
    let pixelLen = code > 255 ? fontsize : fontsize / 2

    curLen += pixelLen

    if (curLen > width) {
      end = i
      if (result.length === line - 1) {
        end = end - 2 < 0 ? 0 : end - 2
        result.push(str.substring(start, end) + '...')
      } else {
        result.push(str.substring(start, end))
      }
      start = i
      curLen = pixelLen
    }
    if (i === str.length - 1 && result.length !== line) {
      end = i
      result.push(str.substring(start, end + 1))
    }
  }

  return result
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值