27 lines
988 B
JavaScript
27 lines
988 B
JavaScript
'use strict';
|
|
|
|
function findAlphaBounds(rgba, width, height, threshold = 4) {
|
|
let left = width, top = height, right = 0, bottom = 0;
|
|
for (let y = 0; y < height; y++) {
|
|
for (let x = 0; x < width; x++) {
|
|
if (rgba[(y * width + x) * 4 + 3] <= threshold) continue;
|
|
left = Math.min(left, x);
|
|
top = Math.min(top, y);
|
|
right = Math.max(right, x + 1);
|
|
bottom = Math.max(bottom, y + 1);
|
|
}
|
|
}
|
|
return right > left && bottom > top ? { left, top, right, bottom } : null;
|
|
}
|
|
|
|
function toWorldBounds(pixels, width, height, scale, centerX, centerY) {
|
|
if (!pixels || !isFinite(scale) || scale <= 0) return null;
|
|
const left = centerX + (pixels.left - width / 2) / scale;
|
|
const right = centerX + (pixels.right - width / 2) / scale;
|
|
const top = centerY - (pixels.top - height / 2) / scale;
|
|
const bottom = centerY - (pixels.bottom - height / 2) / scale;
|
|
return { x: left, y: bottom, width: right - left, height: top - bottom };
|
|
}
|
|
|
|
module.exports = { findAlphaBounds, toWorldBounds };
|