最近项目需求使用canvas绘制朋友圈可分享的海报,中间遇到很多问题,于是上网搜索,完美解决后,在此总结一下。
先来看一下效果图,点击按钮生成带二维码的图片。
1.关于canvas画布的宽度和高度
wxml:
<canvas canvas-id="canvasId" style="width:{{canvasWidth}}px;height:{{canvasHeight}}px;background:red;position:fixed;top:-10000px;left:0; right:0;" disable-scroll="true" ></canvas>
JS
let windowWidth = wx.getSystemInfoSync().windowWidth;
let windowHeight = wx.getSystemInfoSync().windowHeight;
let scale = wx.getSystemInfoSync().pixelRatio
let canvasHeight = windowHeight * scale
let canvasWidth = windowWidth * scale;
2.绘制背景图片
注意:绘制的背景图片高度不能超过canvas的高度,否则部分手机会出现黑屏的情况
ctx.drawImage('/images/image/backgroundImage.png', 0, 0, canvasWidth, canvasHeight);
3.绘制中间白色区域
// x,y为白色区域起始坐标
let x = 15 * scale;
let y = 48 * scale;
ctx.setFillStyle('#fff');
//contentHeight白色区域的高度
let contentHeight = 516 * scale
// contentWidth为白色区域的宽度
let contentWidth = this.data.canvasWidth - x * 2
//绘制borderRadius 为30 的 白色区域
ctx.moveTo(x + 30, y)
ctx.arcTo(x + contentWidth, y, x + contentWidth, y + contentHeight, 20);
ctx.arcTo(x + contentWidth, y + contentHeight, x, y + contentHeight, 20);
ctx.arcTo(x, y + contentHeight, x, y, 20);
ctx.arcTo(x, y, x + contentWidth , y, 20);
ctx.fill()
4.绘制换行文字
//contentMaxWidth 为 中间内容的最大宽度 如果超过此宽度需要换行
let strs = [];
let rowWidth = 0.0
for (let c of typeName) {
let cw = ctx.measureText(c).width ;
// 判断有没有换行符
if ((rowWidth + cw) >= contentMaxWidth ) {
// 文字需要换行了
let str = strs.join('');
ctx.fillText(str, x, y)
// 换行、清空
y += 33 * scale;
strs.length = 0;
rowWidth = 0.0;
}
strs.push(c);
rowWidth += cw;
}
if (strs.length > 0) {
let str = strs.join('');
ctx.fillText(str, x, y)
}
5.绘制居中的圆形太阳码图片
ctx.save()
//proCodeWidth为二维码的宽度 proCodeX为居中后的X起始点坐标
let proCodeWidth = 97 * scale
let proCodeX = (this.data.canvasWidth - proCodeWidth) / 2
ctx.arc((proCodeX + 48.5) * scale, y + 48.5 * scale, 48.5 * scale, 0, 2 * Math.PI, false)
ctx.clip()
ctx.drawImage(this.data.proCode, proCodeX, y, 97 * scale, 97 *scale);
ctx.restore();
6.本地生成太阳码
因为canvas.drawImage 是不支持网络图片的,只支持本地图片。所以我们需要把从后台获取到的太阳码转换为本地图片。 这里可以采用微信官方提供的 wx.getImageInfo 或者 wx.downloadFile。(网络图片需先配置download域名才能生效)
wx.getImageInfo({
src: url,
success: (res) => {
this.setData({
proCode: res.path
})
console.log(this.data.proCode)
},
fail: (err) => {
console.log(err)
}
})
7.绘制居中的文字
let tip ='应手-让招聘更加得心应手'
//144为文字的宽度 或者你也可以采用ctx.measureText(tip).width来获取
let tipX = (this.data.canvasWidth - 144 * scale) / 2
let tipY = 616.5 * scale
ctx.fillText(tip, tipX, tipY)
8.把canvas转为图片保存在本地
ctx.draw(false, () => {
let self = this
setTimeout(() => {
wx.canvasToTempFilePath({
canvasId: 'canvasId',
success(res) {
wx.previewImage({
current: res.tempFilePath,
urls: [res.tempFilePath]
});
},
fail: function (err) {
console.log('绘制失败, 请重试');
}
}, self)
}, 500)
})
这样就可以生成海报并保存在本地,第一次写文章,如果有错误欢迎指正。