canvs 主要是用于小程序生成图片,接下来讲一下生成图片相关的函数
Taro.getSystemInfo({
success: function(res) {
that.setState({
screenWidth: res.screenWidth,
screenHeight: res.screenHeight
})
}
})
drawList() {
const { defaultWidth, defaultHeight, screenWidth } = this.state;
let i = 100;
let height = 0;
const cvsCtx = Taro.createCanvasContext('poster', this.$scope);
cvsCtx.setFillStyle('white')
cvsCtx.fillRect(0, 0, screenWidth, defaultHeight+height)
cvsCtx.setFontSize(14)
cvsCtx.fillStyle = "white";
cvsCtx.fillRect(0, 0, 375, 40+height);
cvsCtx.setFillStyle('black')
cvsCtx.fillText('名称:', 20, 25+height);
cvsCtx.fillText(name, 60, 25+height);
cvsCtx.strokeStyle = "#eee"; //横线颜色
cvsCtx.fillStyle = "#eee";
...
cvsCtx.draw();
}
// 生成图片
sevePicture() {
const { screenWidth, finalHeight, finish } = this.state;
const that = this;
if (finish) {
Taro.canvasToTempFilePath({ // 调用小程序API对canvas转换成图
x: 0, // 开始截取的X轴
y: 0, // 开始截取的Y轴
width: screenWidth, // 开始截取宽度
height: finalHeight, // 开始截取高度
destWidth: screenWidth*2, // 截取后图片的宽度(避免图片过于模糊,建议2倍于截取宽度)
destHeight: finalHeight*2, // 截取后图片的高度(避免图片过于模糊,建议2倍于截取宽度)
canvasId: 'poster', // 截取的canvas对象
success: function (res) { // 转换成功生成临时链接并调用保存方法
that.setState({
tempFilePath: res.tempFilePath
})
},
fail: function (res) {
console.log('绘制临时路径失败')
}
}, this.$scope)
}
}
// 保存图片
saveImage() {
const { tempFilePath } = this.state;
const that = this;
Taro.showLoading({
title: '正在保存图片...',
})
Taro.getSetting({
success() {
Taro.authorize({
scope: 'scope.writePhotosAlbum', // 保存图片固定写法
success() {
// 图片保存到本地
Taro.saveImageToPhotosAlbum({
filePath: tempFilePath, // 放入canvas生成的临时链接
success() {
Taro.hideLoading();
Taro.showToast({
title: '保存成功',
icon: 'success',
duration: 4000
})
}
})
},
fail() {
Taro.hideLoading();
Taro.showToast({
title: '您点击了拒绝微信保存图片,再次保存图片需要您进行截屏',
icon: 'none',
duration: 3000
})
}
})
},
fail() {
Taro.hideLoading();
Taro.showToast({
title: '请先输入数据',
icon: 'none',
duration: 3000
})
}
})
}
至此,微信小程序生成图片后保存的功能就做好了,其实开发者只需要处理中间第二步,就是将什么东西画在画布上,将画什么处理好就好了,其他只需要调用接口就好了
<View style='position:fixed;top:9999rpx;'>
<Canvas style={{ width: `${screenWidth}PX`, height: '5000PX', position: "absolute", left: 0, top: 0, zIndex: 99}} canvasId='poster' />
</View>
//或者
<Canvas>
<cov canvasId='poster'er-view></cover_view>
</canvas>