今天项目中,需要把echarts转换成图片的格式传递给后端,也是踩了不少坑,特地记录一下,
云开发(并不推荐)
云开发只是开发者可以操作云存储,用户是不能操作的
1.wxml的echaets 加一个id (渲染echarts就不说了吧)
<view class="content echart-position">
<!-- <view class="char_content"> -->
<ec-canvas id="line" canvas-id="line" ec="{{ ec }}"></ec-canvas>
<!-- </view> -->
</view>
2.我绑定了一个按钮 加一个点击事件,这都简单,
不会有人连点击事件都不会吧,
3.就开始了 点击事件了
因为保存的图片是临时文件,所以我把他传到云开发 也就是云端 在通过 getTempFileURL 拿到路径就好了
save() {
const ecComponent = this.selectComponent('#line'); //找到echarts
console.log(ecComponent)
var that = this
// 先保存图片到临时的本地文件,
ecComponent.canvasToTempFilePath({
success: res => {
console.log(res) //临时路径
wx.cloud.init({}); //格式化云端
// 把图片传到云端
wx.cloud.uploadFile({
cloudPath: new Date().getTime() + '.png',
filePath: res.tempFilePath,
success: res => {
// 返回的是 图片的云端地址
console.log(res.fileID)
// 通过getTempFileURL 可以获取到 暂时的线上地址
wx.cloud.getTempFileURL({
fileList: [res.fileID],
success: res => {
console.log(res.fileList[0].tempFileURL)
},
fail: console.error
})
}
});
return
},
fail: res => console.log(res)
});
},
4.云开发,里面可以看到我们的图片,nice 下课
base 64 图片传递(已经解决)
1.转换的方法封装起来
base64({ url, type }) {
return new Promise((resolve, reject) => {
wx.getFileSystemManager().readFile({
filePath: url, //选择图片返回的相对路径
encoding: 'base64', //编码格式
success: res => {
resolve('data:image/' + type.toLocaleLowerCase() + ';base64,' + res.data)
},
fail: res => reject(res.errMsg)
})
})
},
2.在进入页面的时间,就获取到echarts的临时路径 通过调用函数转换成base 64位 由于echarts的 画布机制,避免我们拿不到数据加一个定时器
onLoad: function() {
setTimeout(() => {
var that = this
const ecComponent = this.selectComponent('#line'); //找到echarts
console.log(ecComponent)
ecComponent.canvasToTempFilePath({
success: res => {
console.log(res) //临时路径
that.base64({
url: res.tempFilePath,
type: 'png'
}).then(ress => {
console.log(ress)
that.setData({
bigImg: ress,
})
})
}
});
console.log("onLoad")
}, 2000)
},
拿到就可以发起请求了,