<canvas canvas-id="canvas" style="width:{{cWidth}}px;height:{{cHeight}}px;visibility:hidden;position:absolute;top:-10000rpx;left:-10000rpx;"></canvas>
<van-uploader bind:after-read="onRead" wx:if="{{goodsItem.imgFile}}">
<image src="{{goodsItem.imgFile}}" class='camera'></image>
</van-uploader>
//使用vant组件或者使用wx.chooseImage都可以
onRead(res1) {
var that = this
var imgPath = res1.detail.file.url
var imgFile = 'goodsItem.imgFile'
that.setData({
[imgFile]:imgPath,
})
wx.getImageInfo({
src:imgPath,
success:function(res){
var ratio = 2;
var canvasWidth = res.width //图片原始长宽
var canvasHeight = res.height
while (canvasWidth > 400 || canvasHeight > 400){// 保证宽高在400以内
canvasWidth = Math.trunc(res.width / ratio)
canvasHeight = Math.trunc(res.height / ratio)
ratio++;
}
that.setData({
cWidth: canvasWidth,
cHeight: canvasHeight
})
//----------绘制图形并取出图片路径--------------
var ctx = wx.createCanvasContext('canvas')
ctx.drawImage(res.path, 0, 0, canvasWidth, canvasHeight)
ctx.draw(false, setTimeout(function(){
wx.canvasToTempFilePath({
canvasId: 'canvas',
destWidth: canvasWidth,
destHeight: canvasHeight,
success: function (res) {
var filePath = res.tempFilePath
wx.getFileSystemManager().readFile({
filePath,
encoding: 'base64',
success:(res) =>{
// console.log('data:image/png;base64,' + res.data)
that.setData({
file:'data:image/png;base64,' + res.data
})
}
})
},
fail: function (res) {
console.log(res.errMsg)
}
})
},100))
}
})
},
网友评论