微信小程序 canvas绘制多行文本(文本换行)
2019-03-22 本文已影响0人
阿昕_
支持程度
支持程度.png效果图
中文.png 单词不截断.png 单词截断.png代码实现
/**
*【drawTxt】canvas 绘制多行文本
*【TODO: 中英混排且考虑单词截断...】
*
* @param {*} context 绘制上下文环境 【必传】
* @param {*} scale 缩放比 windowWidth / 750
* @param {*} text 文本内容
* @param {*} broken 单词是否截断显示 【true 如果不考虑英文单词的完整性 适用于所有情况】 【false 考虑英文单词的完整性 仅适用于纯英文】
* @param {*} fillStyle 文本颜色
* @param {*} fontSize 文本大小
* @param {*} x 文本左上角x坐标
* @param {*} y 文本左上角y坐标
* @param {*} lineHeight 行高
* @param {*} maxWidth 最大宽度
* @returns 此次绘制文本的高度 单位: px
*/
function drawTxt({context, scale = 0.5, text = 'test text', fillStyle = '#000', broken = true, ...rest}) {
if (!context) throw Error('请传入绘制上下文环境context')
// 默认设置
let origin = {x: 0, y: 0, lineHeight: 30, maxWidth: 630 , fontSize: 28}
// 比例计算正确的尺寸
for (let item in rest) {
rest[item] *= scale
}
// 获取计算后的值
let {x, y, lineHeight, maxWidth, fontSize} = {...origin, ...rest}
// 设置字体样式
context.setTextAlign('left')
context.setTextBaseline('top')
context.setFillStyle(fillStyle)
context.setFontSize(fontSize)
// broken: true 如果不考虑英文单词的完整性 适用于所有情况
// broken: false 考虑英文单词的完整性 仅适用于纯英文
//【TODO: 中英混排且考虑单词截断...】
let splitChar = broken ? '' : ' '
let arrText = text.split(splitChar)
let line = ''
let linesCount = 0
for (var n = 0; n < arrText.length; n++) {
let testLine = line + arrText[n] + splitChar
let testWidth = context.measureText(testLine).width
if (testWidth > maxWidth && n > 0) {
// 一行已经绘制完成
linesCount++
context.fillText(line, x, y)
line = arrText[n] + splitChar
y += lineHeight
} else {
// 一行还未绘制完成
line = testLine
}
}
linesCount++
context.fillText(line, x, y)
return linesCount * lineHeight
}
//【drawTxt example】
// let drawTxtHeight = drawTxt({
// context,
// scale,
// text: 'Free Classifieds Using Them To Promote Your Stuff Online',
// broken: false,
// fillStyle: '#ccc',
// x: 0,
// y: 0,
// lineHeight: 66,
// maxWidth: 630,
// fontsize: 48
// })
// console.log(`此次绘制总高度:${drawTxtHeight}px`)
结语
有什么问题尽管留言~
wepy常用封装
由于我平时主要使用wepy开发项目 所以这些常用封装及项目架子都是使用的wepy
覆盖了一些常用操作与封装、登录流程、保存图片至相册及相关授权流程
所有常用封装及流程实现请点我前往GitHub查看https://github.com/webxing/wepy_skeleton
项目目录结构
.
├── README.md
└── wepy_skeleton
├── package.json // 配置启动脚本 (debug/dev/build)
├── project.config.json
├── src
│ ├── app.wpy // networkTimeout plugins this.use('promisify') 拦截request请求
│ ├── common
│ │ ├── animate.wxss // 动画支持
│ │ ├── api.js // 所有api
│ │ ├── collectFormId.js // 收集formId
│ │ ├── common.js // 封装一些公用方法
│ │ ├── decorator.js // 封装trycatch装饰器 实现对函数的错误监控
│ │ ├── http.js // 封装小程序request请求
│ │ ├── bindEvent.js // 当n个触发条件均满足时 触发函数
│ │ └── storage.js // 封装storage为promise
│ ├── components
│ │ └── Modal.wpy // 错误弹窗
│ └── pages
│ └── index.wpy // 登录流程 引入装饰器trycatch 配置错误处理handleError
│ └── sign.wpy // 保存图片至相册及相关授权处理
│ └── auth.wpy // 授权页
└── wepy.config.js // 配置rootURL 配置Less autoprefix 配置drop_console drop_debugger