微信小程序wx.createCanvasContext停止维护了,文档又说的不是太清楚,研究并记录下来如何生成实例的。
并且推荐另一种画海报的方式:微信小程序生成海报_工具人小胡的博客-CSDN博客_小程序海报
<view>
<text bindtap="up_img" >上传图片</text>
<view style="top:-6000px; position: absolute;">
<canvas type="2d" style="width:5000px;height:5000px" id="shareBox" ></canvas>
</view>
</view>
Page({
data:{}
init(res) {
const canvas = res[0].node
const ctx = canvas.getContext('2d')
const dpr = wx.getSystemInfoSync().pixelRatio
canvas.width = res[0].width * dpr
canvas.height = res[0].height * dpr
this.setData({
canvas,
ctx
});
ctx.scale(dpr, dpr);
},
getimg(img_file) { //压缩图片
return new Promise((resolve, reject) => {
wx.getImageInfo({
src: img_file,
success: succ => {
let ratio = succ.height / succ.width
if (this.data.originHeight == 0) {
this.data.originHeight = succ.height * 0.7;
this.data.originWidth = succ.height * ratio;
} else {
this.data.originHeight = this.data.originHeight * 0.7
this.data.originWidth = this.data.originHeight * ratio
}
let Img = this.data.canvas.createImage(); //创建img对象
Img.src = img_file
Img.onload = () => {
this.data.ctx.drawImage(Img, 0, 0, Math.ceil(this.data.originWidth), Math.ceil(this.data.originHeight));
wx.canvasToTempFilePath({ //将canvas生成图片
canvas: this.data.canvas,
x: 0,
y: 0,
width: this.data.originWidth,
height: this.data.originHeight,
destWidth: this.data.originWidth,
destHeight: this.data.originHeight,
success: function (res) {
wx.getFileInfo({
filePath: res.tempFilePath,
success(ree) {
if (ree.size > 1000000) {
reject();
} else {
wx.hideLoading();
resolve(res.tempFilePath)
}
return
}
})
return
},
}, this)
}
}
})
})
},
up_img(e) {
wx.chooseImage({
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: res => {
if (res.tempFiles[0].size > 1000000) {
wx.showLoading({
title: '上传中',
})
let getImg = () => {
this.getimg(res.tempFilePaths[0]).catch(err => {
getImg()
}).then(res => {
if (res) {
this.get_push_img(res)
}
})
}
}else{
wx.showLoading({
title: '上传中',
})
this.get_push_img(res.tempFilePaths[0])
}
}
})
},
get_push_img(file) {
return new Promise((resolve, reject) => {
wx.uploadFile({
url: `/files/upload/up`, //仅为示例,非真实的接口地址
filePath: file,
name: 'file',
formData: {
token: this.data.token_obj.token,
article: 1
},
success(res) {
let data = JSON.parse(res.data)
if (data.code == 200) {
$Message({
content: '上传成功',
type: 'success'
});
resolve(data.result[0].temp_path)
} else {
reject();
}
},
fail: function (err) {
console.log(err)
}
})
})
},
onl oad: function (options) {
const query = wx.createSelectorQuery()
query.select('#shareBox')
.fields({
id: true,
node: true,
size: true
})
.exec(this.init.bind(this));
}
})