我用canvas载入图片:
wx.createSelectorQuery().select('#myCanvas').fields({ node: true, size: true }).exec((res)=>{
const canvas = res[0].node
that.canvas = canvas;
that.context = canvas.getContext('2d')
canvas.width = res[0].width * app.globalData.pixelRatio
canvas.height = res[0].height * app.globalData.pixelRatio
const img = canvas.createImage();
img.src = that.data.url;
img.onload = () => {
//计算图片和canvas的宽高比,对图片进行保持比例缩放。图片可正常按比例载入
that.context.drawImage(img, 0, 0, that.data.scaledWidth/**计算后的图片宽**/, that.data.scaledHeight/**计算后的图片高**/);
}
}
confirmTap: function () {
var that = this;
wx.showLoading({
title: '正在保存图片',
})
setTimeout(() => {
wx.canvasToTempFilePath({
x: 0,
y: 0,
width: that.data.scaledWidth,
height: that.data.scaledHeight,
destWidth: that.data.scaledWidth * app.globalData.pixelRatio, /**app.globalData.pixelRatio为像素比**/
destHeight: that.data.scaledHeight * app.globalData.pixelRatio,
// width: 10,
// height: 10,
// destHeight: 300,
// destWidth: 300,
fileType: 'jpg',
canvas: this.canvas,
success: function (res) {
console.log(res);
var tempFilePath = res.tempFilePath;
console.log(tempFilePath);
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success:function(res){
wx.hideLoading()
}
})
}
})
}, 1500);
}
但实际保存的图片是整个canvas的宽高,但被缩放成that.data.scaledWidth * app.globalData.pixelRatio和that.data.scaledHeight * app.globalData.pixelRatio
加载时的图片
保存的图片
有没有试过destWidth不乘像素比,直接乘倍数,看是不是正常的?我一般生成海报,保存到相册等等都是乘以倍数,修改成下面的试试
canvas.width = res[0].width canvas.height = res[0].height destWidth: that.data.scaledWidth * 3, /**app.globalData.pixelRatio为像素比**/ destHeight: that.data.scaledHeight * 3,
然后获取scaledWidth和scaledHeight的代码:
奇怪的是偶尔会正常