前言:微信小程序里面有趣的东西很多,canvas画布就是其中一个,而且微信小程序提供了很便捷的API用于将画布生成图片,并提供了API用于将图片保存到用户相册中。
一、实现过程
①、测试图片
②、实现代码
<!-- test.wxml -->
<!-- 这里的测试图片是宽度为750px 高度为350px, 我直接将canvas的宽度,高度用rpx设置了 -->
<canvas
canvas-id="gameCanvas"
style="width:750rpx; height:350rpx"
></canvas>
<button bindtap="createImage">生成图片</button>
//test.js
Page({
data:{
imagePath:\'./image/test.png\',
imageWidth:\'\',
imageHeight:\'\',
},
onReady: function(){
let _this = this,
deviceWidth = 0;
//获取设备宽度,用于求所需画在画布上的图片的高度
wx.getSystemInfo({
success:function(res){
deviceWidth = res.windowWidth; //获取设备宽度
wx.getImageInfo({ //获取图片信息
src: _this.data.imagePath,
success: function(res){
let imageWidth = deviceWidth,
imageHeight = deviceWidth/res.width*res.height; //求所需画在画布上的图片的高度
_this.setData({
\'imageWidth\': imageWidth,
\'imageHeight\':imageHeight
});
const ctx = wx.createCanvasContext(\'gameCanvas\'); //创建画布对象
ctx.drawImage(_this.data.imagePath, 0, 0, imageWidth, imageHeight); //添加图片
ctx.setFontSize(16); //设置字体大小
ctx.setFillStyle(\'blue\'); //设置字体颜色
ctx.fillText(\'你的名字\', imageWidth/2, imageHeight/2); //设置字体内容、坐标
ctx.draw(); //开始绘画
}
})
}
});
},
createImage: function(){
let imageWidth = this.data.imageWidth,
imageHeight = this.data.imageHeight;
wx.canvasToTempFilePath({ //将canvas生成图片
canvasId: \'gameCanvas\',
x: 0,
y: 0,
width: imageWidth,
height: imageHeight,
destWidth: imageWidth, //截取canvas的宽度
destHeight: imageHeight, //截取canvas的高度
success: function (res) {
wx.saveImageToPhotosAlbum({ //保存图片到相册
filePath: res.tempFilePath,
success: function () {
wx.showToast({
title: "生成图片成功!",
duration: 2000
})
}
})
}
})
}
});
③、实现效果
点击成功图片后,小程序先会进行询问"是否给访问相册的权限",如果用户确定了,就可以将图片保存到相册啦。