HTML5 Canvas实现自动换行和竖排文本

Canvas的渣渣API不支持自动换行和竖排,找了一下没有满意的解决方案,只好自己写一个了。

方法1:根据文字尺寸计算在哪换行

// 画个框用来调试
const DEBUG = true

// 画文本,支持多行、自动换行、竖排文字
function drawText (ctx, text, x, y, width, height, hasStroke = false, isVertical = false) {
   
  if (DEBUG) {
    let [oldLineWidth, oldStrokeStyle] = [ctx.lineWidth, ctx.strokeStyle];
    [ctx.lineWidth, ctx.strokeStyle] = [1, 'red']
    ctx.strokeRect(x, y, width, height);
    [ctx.lineWidth, ctx.strokeStyle] = [oldLineWidth, oldStrokeStyle]
  }

  if (!isVertical) {
    drawTextHorizontal(ctx, text, x, y, width, height, hasStroke)
  } else {
    drawTextVertical(ctx, text, x, y, width, height, hasStroke)
  }
}

// 画横排文本,垂直居中,可以垂直溢出
function drawTextHorizontal (ctx, text, x, y, width, height, hasStroke = false) {
   
  let oldBaseLine = ctx.textBaseline
  ctx.textBaseline = 'hanging'
  let lineHeight = parseInt(ctx.font) // ctx.font必须以'XXpx'开头

  // 计算每一行
  let lines = []
  let curLine = ''
  for (let char of text) {
    let nextLine = curLine + char
    if (char === '\n' || ctx.measureText(nextLine).width > width) {
      lines.push(curLine)
      curLine = char === '\n' ? '' : char
    } else {
      curLine = nextLine
    }
  }
  lines.push(curLine)

  // 逐行画文本
  let lineY = y + (height - lineHeight * lines.length) / 2
  for (
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值