canvas
已知微信停止更新了wx.createCanvasContextAPI,推荐采用新版本canvas
由于我是没有接触过老版本的新手,就学些纪录了下新版本的用法,其中还有很多方法我并不知道,微信官方文档也不写清楚。但是勉勉强强还是可以绘制个海报的。
API
wx.createSelectQuery()
canvas.getContext()
wxml
css
<view>
<view style="padding: 20rpx 40rpx;box-sizing: border-box;width: 750rpx;height: 1000rpx;background-color: #f1f1f1;">
<canvas type="2d" id="myCanvas" style="width: 100%;height: 100%;" />
</view>
<button bind:tap="renderToCanvas">绘制canvas</button>
</view>
arduino
// 通过wx.createSelectQuery()获取canvas元素节点
wx.createSelectorQuery()
.select('#myCanvas')
.fields({
node: true,
size: true
})
.exec(res => {
const canvas = res[0].node
// 创建canvas对象
const ctx = canvas.getContext('2d');
})
canvas是可以设置画布宽高
ini
const renderWidth = res[0].width;
const renderHeight = res[0].height;
const dpr = wx.getWindowInfo().pixelRatio;//获取像素比 - 针对不同设备进行适配
let canvasWidth = renderWidth * dpr;
let canvasHeight = renderHeight * dpr;
// 重新设置画布宽高
canvas.width = canvasWidth;
canvas.height = canvasHeight;
此时画布就已经准备好了,我们就可以在画布上进行绘制各种元素
arduino
drawCanvas(canvas,ctx, width, height) {
// 清空画布
ctx.clearRect(0, 0, width, height);
// 若干绘制调用
ctx.fillStyle = '#fff';// 设置填充色
ctx.fillRect(0, 0, width, height);//绘制矩形
const image1 = canvas.createImage()//创建第一个图片
this.drawImageToCanvas(image1,ctx,0,0,width,100,'https://open.weixin.qq.com/zh_CN/htmledition/res/assets/res-design-download/icon64_wx_logo.png')
ctx.fillStyle = '#e8e8e8';
ctx.fillRect(0, 100, width, width);
const image2 = canvas.createImage()
// 中心坐标
let centerX = width / 2;
let centerY = width / 2 + 100;
this.drawImageToCanvas(image2,ctx,centerX - centerX / 2,centerY - centerX / 2,centerX,centerX,'https://open.weixin.qq.com/zh_CN/htmledition/res/assets/res-design-download/icon64_wx_logo.png')
// 底部二维码
const image3 = canvas.createImage()
this.drawImageToCanvas(image3,ctx,20,width + 100 + 20,160,160,'https://open.weixin.qq.com/zh_CN/htmledition/res/assets/res-design-download/icon64_wx_logo.png')
// 设置文字样式
ctx.font = '36px Arial';
ctx.fillStyle = '#000'; // 文字颜色
// 在指定位置绘制文字
this.drawWrappedText(ctx,'点赞关注不迷路,有我有你不孤单',240,width + 100 + 70,width / 2,50)
wx.canvasToTempFilePath({
canvas: canvas,
success(res) {
console.log(res);
}
})
},
因为需要多次调用这个绘制图片的方法,所以我进行了封装
scss
drawImageToCanvas(imgObj,ctx,x,y,w,h,src){// 参数 - 图片对象,ctx,x偏移量,y偏移量,图片宽,图片高,图片源
imgObj.onload = () => {
ctx.drawImage(
imgObj,
x,
y,
w,
h,
)
}
imgObj.src = src;
},
canvas不能使文本自动换行,使用js文本自动换行方法
ini
drawWrappedText(ctx, text, x, y, maxWidth, lineHeight) {// 参数 - ctx,文本源,x偏移量,y偏移量,容器最大宽,行高
let words = text.split('');
let line = '';
for (let i = 0; i < words.length; i++) {
let testLine = line + words[i] + '';
let metrics = ctx.measureText(testLine);//measureText可以解析文字的信息
let testWidth = metrics.width;// 计算当前n个文字的宽度,判断是否换行
if (testWidth > maxWidth && i > 0) {
ctx.fillText(line, x, y);
line = words[i] + '';
y += lineHeight;
} else {
line = testLine;
}
}
ctx.fillText(line, x, y);
},

这只是一个简单的案例,相信海报大致就使用这些方法了。