真机截图(正常):
iphone 7中截图(图片发生了裁剪):
核心代码片段(具体见代码片段:https://developers.weixin.qq.com/s/fUJ4d3m17UxT):
<view class="page">
<canvas
type="2d"
style="width:{{canvasWidth}}px;height:{{canvasHeight}}px;"
id="myCanvas"
class="myCanvas"
></canvas>
<image src="{{imageSrc}}" mode="widthFix"></image>
</view>
const app = getApp()
Page({
data: {
imageSrc: "",
canvasWidth: '',
canvasHeight: '',
imageSrc:""
},
onLoad: async function () {
let imageSrc = './1.jpg';
let imageInfo = await this.getImageInfo(imageSrc);
let r = 2.165914247136675;
let canvasWidth = Math.abs(imageInfo.width / r);
let canvasHeight = Math.abs(imageInfo.height / imageInfo.width*canvasWidth);
this.setData({
canvasWidth,
canvasHeight
},async ()=>{
let {
canvas,
context
} = await this.initCanvas('#myCanvas', 1);
let img = await this.createImage(canvas, imageSrc);
context.drawImage(img, 0, 0, imageInfo.width, imageInfo.height, 0, 0, canvasWidth, canvasHeight)
let src = await wx.canvasToTempFilePath({
x: 0,
y: 0,
width:canvasWidth,
height:canvasHeight,
destWidth:canvasWidth,
destHeight:canvasHeight,
canvas,
success:(res)=>{
this.setData({
imageSrc:res.tempFilePath
})
}
})
})
},
getImageInfo(src) {
return new Promise(async (resolve, reject) => {
wx.getImageInfo({
src,
success: (result) => {
resolve(result);
},
fail: (e) => {
reject(e);
}
});
});
},
initCanvas(selector, dpr) {
return new Promise((resolve, reject) => {
wx.createSelectorQuery()
.select(selector)
.fields({
node: !0,
size: !0
})
.exec((res) => {
let canvasWidth = res[0].width;
let canvasHeight = res[0].height;
let canvas = res[0].node;
let context = canvas.getContext('2d');
canvas.width = canvasWidth * dpr;
canvas.height = canvasHeight * dpr;
context.scale(dpr, dpr);
resolve({
context,
canvas,
canvasWidth,
canvasHeight
});
});
});
},
createImage(ctxNode, imageSrc) {
return new Promise((resolve, reject) => {
const img = ctxNode.createImage();
img.src = imageSrc;
img.onload = () => {
resolve(img);
};
});
}
})
drawImage这一步是正常的,就是canvasToTempFilePath的时候发生了裁剪
楼主解决了吗?怎么解决的
initCanvas 应该传 wx.getSystemInfoSync().pixelRatio 而不是固定值 1