原始图片是 400x500 的网格图,就是红色框内的样子。
红色框内是在 canvas 上绘制的等比例原图,蓝色框内是通过 wx.canvasToTempFilePath 输出的图片分片,但是生成的图片比例大小明显和 canvas 不一致,是哪里的问题?
<canvas type="2d" id="canvas" style="width:{{containerW}};height:{{containerH}}"></canvas>
<view class="grid" style="width:{{containerW}};height:{{containerH}}">
<view class="cell" wx:for="{{pieces}}" style="width:{{item.width}};height:{{item.height}}">
<image src="{{item.src}}" />
</view>
</view>
Page({
data: {
containerW: '',
containerH: '',
pieces: [],
},
onReady() {
const cols = 4;
const rows = 5;
const containerW = wx.getSystemInfoSync().windowWidth * .5;
const containerH = containerW * rows / cols;
this.setData({
containerW: `${containerW}px`,
containerH: `${containerH}px`,
});
wx
.createSelectorQuery()
.select('#canvas')
.fields({ node: true })
.exec((res) => {
const canvas = res[0].node;
const ctx = canvas.getContext('2d');
const img = canvas.createImage();
canvas.width = 400;
canvas.height = 500;
img.onload = () => {
ctx.drawImage(img, 0, 0);
const promises = [];
const cellW = containerW / cols;
const cellH = containerH / rows;
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
promises.push(new Promise((resolve, reject) => {
wx.canvasToTempFilePath({
x: col * cellW,
y: row * cellH,
width: cellW,
height: cellH,
canvas,
fileType: 'jpg',
success: res => resolve({
width: `${cellW}px`,
height: `${cellH}px`,
src: res.tempFilePath,
}),
fail: res => reject(new Error(res.errMsg)),
});
}));
}
}
Promise.all(promises).then(pieces => this.setData({ pieces }));
};
img.src = 'pic.png';
});
},
});
很坑!!
没人遇到这问题吗?