小程序 实现canvas中文字换行

野性酷女 2022-05-09 18:28 329阅读 0赞

实现canvas中文字换行

  1. const ctx = wx.createCanvasContext('shareImg');
  2. ctx.setFontSize(15);
  3. ctx.setFillStyle('#333333');
  4. let str = 'RumbaTime时尚手表潮流时装女表电子钢带石英表美国正品进口表';
  5. that.drawText(ctx, str, 45, ImgHeight + 70, 30, 265);// 调用行文本换行函数
  6. /**
  7. * 绘制多行文本
  8. * @param ctx canvas对象
  9. * @param str 文本
  10. * @param leftWidth 距离左侧的距离
  11. * @param initHeight 距离顶部的距离
  12. * @param titleHeight 文本的高度
  13. * @param canvasWidth 文本的宽度
  14. * @returns {*}
  15. */
  16. drawText: function(ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
  17. let lineWidth = 0;
  18. let lastSubStrIndex = 0; //每次开始截取的字符串的索引
  19. for (let i = 0; i < str.length; i++) {
  20. lineWidth += ctx.measureText(str[i]).width;
  21. if (lineWidth > canvasWidth) {
  22. ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分
  23. initHeight += 22; //22为 文字大小20 + 2
  24. lineWidth = 0;
  25. lastSubStrIndex = i;
  26. titleHeight += 22;
  27. }
  28. if (i == str.length - 1) { //绘制剩余部分
  29. ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
  30. }
  31. }
  32. // 标题border-bottom 线距顶部距离
  33. titleHeight = titleHeight + 10;
  34. return titleHeight;
  35. },

发表评论

表情:
评论列表 (有 0 条评论,329人围观)

还没有评论,来说两句吧...

相关阅读