- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
interface Inset
{
top?: number;
left?: number;
right?: number;
bottom?: number;
}
/**
* Trim transparent borders from a canvas
* @memberof PIXI.utils
* @function trimCanvas
* @param {HTMLCanvasElement} canvas - the canvas to trim
* @returns {object} Trim data
*/
export function trimCanvas(canvas: HTMLCanvasElement): {width: number; height: number; data?: ImageData}
{
// https://gist.github.com/remy/784508
let width = canvas.width;
let height = canvas.height;
const context = canvas.getContext('2d');
const imageData = context.getImageData(0, 0, width, height);
const pixels = imageData.data;
const len = pixels.length;
const bound: Inset = {
top: null,
left: null,
right: null,
bottom: null,
};
let data = null;
let i;
let x;
let y;
for (i = 0; i < len; i += 4)
{
if (pixels[i + 3] !== 0)
{
x = (i / 4) % width;
y = ~~((i / 4) / width);
if (bound.top === null)
{
bound.top = y;
}
if (bound.left === null)
{
bound.left = x;
}
else if (x < bound.left)
{
bound.left = x;
}
if (bound.right === null)
{
bound.right = x + 1;
}
else if (bound.right < x)
{
bound.right = x + 1;
}
if (bound.bottom === null)
{
bound.bottom = y;
}
else if (bound.bottom < y)
{
bound.bottom = y;
}
}
}
if (bound.top !== null)
{
width = bound.right - bound.left;
height = bound.bottom - bound.top + 1;
data = context.getImageData(bound.left, bound.top, width, height);
}
return {
height,
width,
data,
};
}