小程序使用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 天前
小程序学习(二十六)之“订单详情”
小程序
weixin_440058311 天前
2026知识付费小程序:年费全包零抽成,录播题库全功能覆盖
小程序·apache·小程序开发
小羊Yveesss1 天前
2026年微信小程序后端怎么搭建?后台、数据、接口和运维怎么选
运维·微信小程序·小程序
小皮虾1 天前
小程序首页性能优化实战:从 4 秒到 1.8 秒
前端·微信小程序
HackTwoHub1 天前
ARL灯塔重构版:支持APP/小程序/WEB资产同步扫描
人工智能·安全·web安全·网络安全·小程序·重构·自动化
投票竞赛2 天前
避雷按单场活动扣费平台,2026 在线投票测评不限频次新建投票评选活动
小程序
2501_915909062 天前
IPA 深度混淆是什么意思?从混淆强度到实际效果的解读
android·ios·小程序·https·uni-app·iphone·webview
莫名的好感°2 天前
2026家庭快消品采购小程序实测体验
小程序
黄华SJ520it2 天前
新零售排队免单系统开发全流程介绍
小程序·零售·系统开发
衍生星球3 天前
SpringBoot3 + Vue3 + 微信小程序如何学习,以及学哪些技术,组件
sql·微信小程序·uni-app·vue·springboot