canvs 主要是用于小程序生成图片,接下来讲一下生成图片相关的函数
- 初始进入页面的时候就调用API获得设备信息
Taro.getSystemInfo() 获取设置的基本信息
Taro.getSystemInfo({
success: function(res) {
that.setState({
screenWidth: res.screenWidth,
screenHeight: res.screenHeight
})
}
})
- 获取信息在将需要生成的信息画在画布上, 如果你在这一步报错,画布上始终没有东西,那么可能是你这个函数,Taro.createCanvasContext(‘poster’, this.$scope) 没有传第二个参数导致的
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
})
}
})
}
至此,微信小程序生成图片后保存的功能就做好了,其实开发者只需要处理中间第二步,就是将什么东西画在画布上,将画什么处理好就好了,其他只需要调用接口就好了
- canvas 原生优先级
在开发过程中出现一点问题,在微信开发者开具里测试得好好的,一上真机测试就发现,canvas老是跑到最上面来,原因是canvas的在原生里面属于原生组件,它的优先级很高,
方法之一是使用绝对定位,但是你无法使用定位去设置canvas的位置,而是应该在canvas外面在包一层View,然后设置绝对定位
第二个方法是将被他覆盖的view 改为 cover-view,cover-view在小程序中是可以覆盖原生组件的
<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>