小程序使用Canvas设置文字竖向排列

在需要使用的js页面引入js文件,传入对应参数即可

javascript 复制代码
/**
*     文本竖向排列
*/
function drawTextVertical(context, text, x, y) {
  var arrText = text.split('');
  var arrWidth = arrText.map(function (letter) {
    return 26; // 字体间距,需要自定义可以自己加参数,根据传入参数进行设置
  });
  
  var align = context.textAlign;
  var baseline = context.textBaseline;
 
  if (align == 'left') {
    x = x + Math.max.apply(null, arrWidth) / 2;
  } else if (align == 'right') {
    x = x - Math.max.apply(null, arrWidth) / 2;
  }
  if (baseline == 'bottom' || baseline == 'alphabetic' || baseline == 'ideographic') {
    y = y - arrWidth[0] / 2;
  } else if (baseline == 'top' || baseline == 'hanging') {
    y = y + arrWidth[0] / 2;
  }
 
  context.textAlign = 'center';
  context.textBaseline = 'middle';
 
  // 开始逐字绘制
  arrText.forEach(function (letter, index) {
    // 确定下一个字符的纵坐标位置
    var letterWidth = arrWidth[index];
    // 是否需要旋转判断
    var code = letter.charCodeAt(0);
    if (code <= 256) {
      context.translate(x, y);
      // 英文字符,旋转90°
      context.rotate(90 * Math.PI / 180);
      context.translate(-x, -y);
    } else if (index > 0 && text.charCodeAt(index - 1) < 256) {
      // y修正
      y = y + arrWidth[index - 1] / 2;
    }
    context.fillText(letter, x, y);
    // 旋转坐标系还原成初始态
    context.setTransform(1, 0, 0, 1, 0, 0);
    // 确定下一个字符的纵坐标位置
    var letterWidth = arrWidth[index];
    y = y + letterWidth;
  });
  // 水平垂直对齐方式还原
  context.textAlign = align;
  context.textBaseline = baseline;
}
 
module.exports = {
  drawTextVertical: drawTextVertical
}

示例:

引入js

传入参数

页面显示

相关推荐
意会1 小时前
微信闪照小程序实现
前端·css·微信小程序
小白_ysf4 小时前
uniapp 开发微信小程序,获取经纬度并且转化详细地址(单独封装版本)
微信小程序·uni-app
weixin_lynhgworld9 小时前
剧本杀小程序系统开发:构建剧本杀社交新生态
小程序
说私域9 小时前
基于定制开发开源 AI 智能名片 S2B2C 商城小程序的热点与人工下发策略研究
人工智能·小程序
weixin_lynhgworld9 小时前
陪诊小程序系统开发:让就医不再是一件难事
小程序
是一碗螺丝粉1 天前
拯救你的app/小程序审核!一套完美避开审核封禁的URL黑名单机制
前端·javascript·微信小程序
weixin_lynhgworld1 天前
盲盒抽谷机小程序系统开发:从0到1的完整方法论
小程序
weixin_lynhgworld1 天前
短剧小程序系统开发:赋能创作者,推动短剧艺术创新发展
小程序
一匹电信狗1 天前
【C++】异常详解(万字解读)
服务器·c++·算法·leetcode·小程序·stl·visual studio
我叫黑大帅1 天前
微信小程序分包:告别加载慢,像拆快递一样简单!
前端·微信小程序