当使用位图缓冲区时,如下所示:
[50, 50, 50, 255, 50, 50, 50, 255, ...]
[r, g, b, a, r, g, b, a, ...]
我经常像这样使用数学:
let bufferWidth = width * 4;
buffer.forEach((channel, index) => {
let y = Math.floor(index / bufferWidth);
let x = Math.floor((index % bufferWidth) / 4);
let remainder = index % 4;
为了计算x、y或者反过来,以使用平面缓存的位图数据。几乎总是得到翻转的结果,然后通过某种方式将它们翻转回来,但显然我的思考方式有问题。
这个数学公式有什么问题会导致位图被翻转呢?
完整代码,一个裁剪位图的函数:
function crop(
buffer,
width,
height,
leftLimit,
rightLimit,
lowerLimit,
upperLimit
) {
let croppedWidth = rightLimit - leftLimit;
let croppedHeight = upperLimit - lowerLimit;
let length = croppedHeight * croppedWidth * 4;
let bufferWidth = width * 4;
let croppedBuffer = new Uint8Array(length);
buffer.forEach((channel, index) => {
let y = Math.floor(index / bufferWidth);
let x = Math.floor((index % bufferWidth) / 4);
let remainder = index % 4;
let yCropped = y - lowerLimit;
let xCropped = x - leftLimit;
let indexCropped = yCropped * croppedWidth * 4 + xCropped * 4 + remainder;
if (
xCropped >= 0 &&
xCropped <= croppedWidth &&
yCropped >= 0 &&
yCropped <= croppedHeight
) {
croppedBuffer[indexCropped] = buffer[index];
}
});
return croppedBuffer;
}