wxml
- 首先在wxml中用canvas占位,id是后面js根据id在画布上添加东西
- 画布大小可自己设置。如果是要做全屏画布可以动态获取屏幕宽高来设置画布大小
<canvas canvas-id='myCanvas' class='wx-poster' style="width:100%;height:{{bjHeight}}px;"></canvas>
js
- data
data: {
screenWidth: 0,//屏幕宽
screenHeight: 0,//屏幕高
bjWidth:0,//背景图宽度
bjHeight:0,//背景图高度
},
- onLoad
onLoad: function () {
let that = this;
//获取屏幕宽高
wx.getSystemInfo({
success: function(res) {
console.log(res);
that.setData({
screenWidth: res.safeArea.width,
screenHeight: res.safeArea.height,
});
},
})
//如果添加进画布的图片是网络路径要用该api进行转化图片地址
//(canvas不能绘制网络图片,所以调用api 把网路图片转换为本地路径)
//获取图片信息
wx.getImageInfo({
src: '../images/poster_bj.png',
success: res => {
let bjHeight = (res.height*that.data.screenWidth)/(res.width)
console.log(bjHeight)
that.setData({
bjWidth: res.width,
bjHeight
})
}
})
},
- onReady
//可以在改生命周期进去画布绘画
onReady(){
const ctx = wx.createCanvasContext("myCanvas");
//插入背景图片 (图片路径,画布x轴,画布y轴,图片宽度,图片高度)
ctx.drawImage("../images/poster_bj.png", 0, 0, this.data.screenWidth, this.data.bjHeight)
//插入二维码图片
ctx.drawImage("../images/er_code.jpg", 50, 490, 70,70)
//设置字体大小
ctx.setFontSize(14)
//设置字体填充色
ctx.setFillStyle('#FFFFFF')
//插入文字
ctx.fillText('星辰睡眠 与你相盼', 150, 530)
//绘制画布
ctx.draw()
},
如何把画布生成海报
//把画布保存为图片
saveImageToPhotosAlbum(){
wx.showLoading({
title: '图片生成中',
})
//把当前画布指定区域的内容导出生成指定大小的图片
wx.canvasToTempFilePath({
x: 0, //画布x轴起点(默认0)
y: 0, //画布y轴起点(默认0)
width: this.data.screenWidth, //画布宽度(默认为canvas宽度-x)
height: this.data.bjHeight, //画布高度(默认为canvas高度-y)
destWidth: this.data.screenWidth, //输出图片宽度(默认为width)
destHeight: this.data.bjHeight, //输出图片高度(默认为height)
canvasId: "myCanvas", //画布标识,传入 的 canvas-id
fileType: "png", //目标文件的类型,只支持 ‘jpg’ 或 ‘png’。默认为 ‘png’
success: function(res){
console.log(res, "临时文件");
//保存图片到相册
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success(res) {
wx.hideLoading()
wx.navigateBack({
delta: 1,
})
},
fail(res){ console.log("err", res) }
})
},
fail: function(res){
console.log("err", res);
},
}, this);
}