画布下载后台的结果
image.png
项目思路
1.获取图片网络路径
2.调用小程序getSystemInfo() 方法转换路径
3.调用createCanvasContext()绘画画布
.js代码
Page({
data: {
imageWidth: '',
imageHeight: '',
imagepath: 'aaa',
imagearr:
{
back: 'https://xcx.xxx.com.cn/st/d598ab3ea37ddfd60e149062f3771d37.png',
},
},
onReady: function () {
let _this = this,
deviceWidth = 0;
//获取设备宽度,用于求所需画在画布上的图片的高度
wx.getSystemInfo({
success: function (res) {
deviceWidth = res.windowWidth; //获取设备宽度
// 获取 图片转化后的路径
var wimagurl = _this.data.imagearr.back
// _this.getimagepath(wimagurl)
// var headUrl = wx.getStorageSync('back');
wx.getImageInfo({
src: wimagurl,
success: function (res) {
let imageWidth = deviceWidth,
imageHeight = deviceWidth / res.width * res.height; //求所需画在画布上的图片的高度
const ctx = wx.createCanvasContext('gameCanvas'); //创建画布对象
ctx.drawImage(res.path, 0, 0, imageWidth, imageHeight); //添加图片
ctx.draw(); //开始绘画
}
})
}
});
},
createImage: function () {
wx.showLoading({
title: '保存中...'
})
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
})
wx.hideLoading()
wx.showModal({
title: '提示',
content: '您的推广海报已存入手机相册,赶快分享给好友吧',
showCancel: false,
})
},
fail: function (err) {
if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
// 这边微信做过调整,必须要在按钮中触发,因此需要在弹框回调中进行调用
wx.showModal({
title: '提示',
content: '产品授权',
showCancel: false,
})
}
}
})
}
})
},
/**
* msg 网络图片转换为小程序图片
* parameter path str 网络图片路径
* return path str 小程序图片路径
* */
getimagepath: function (path) {
var self = this
wx.getImageInfo({
src: path,
success: function (res) {
wx.setStorage({
key: 'back',
data: res.path,
});
}
})
}
});
.xml代码
<canvas
canvas-id="gameCanvas"
style="width:100%; height:1200rpx"
>
</canvas>
<button bindtap="createImage">生成图片</button>
网友评论