Skip to content

Commit

Permalink
Try manually copying data
Browse files Browse the repository at this point in the history
  • Loading branch information
SuperSodaSea committed Dec 4, 2022
1 parent 60dc669 commit 3de5609
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 9 deletions.
25 changes: 18 additions & 7 deletions packages/utils/src/media/trimCanvas.ts
Expand Up @@ -33,7 +33,7 @@ export function trimCanvas(canvas: ICanvas): { width: number; height: number; da
{
// https://gist.github.com/timdown/021d9c8f2aabc7092df564996f5afbbf

let { width, height } = canvas;
const { width, height } = canvas;

const context = canvas.getContext('2d', {
willReadFrequently: true,
Expand All @@ -55,11 +55,22 @@ export function trimCanvas(canvas: ICanvas): { width: number; height: number; da
while (checkColumn(data, width, left, top, bottom)) ++left;
while (checkColumn(data, width, right, top, bottom)) --right;

width = right - left + 1;
height = bottom - top + 1;
const outputWidth = right - left + 1;
const outputHeight = bottom - top + 1;

return {
width, height,
data: context.getImageData(left, top, width, height),
};
const outputImageData = context.createImageData(outputWidth, outputHeight);
const outputData = outputImageData.data;
const inputStride = 4 * width;
const outputStride = 4 * outputWidth;
let inputIndex = 4 * ((top * width) + left);
let outputIndex = 0;

for (let i = 0; i < outputHeight; ++i)
{
outputData.set(data.slice(inputIndex, inputIndex + outputStride), outputIndex);
inputIndex += inputStride;
outputIndex += outputStride;
}

return { width: outputWidth, height: outputHeight, data: outputImageData };
}
9 changes: 7 additions & 2 deletions packages/utils/test/trimCanvas.tests.ts
Expand Up @@ -26,11 +26,16 @@ describe('trimCanvas', () =>

context.fillStyle = '#ff0000';
context.fillRect(10, 20, 10, 5);
context.fillStyle = '#00ff00';
context.fillRect(15, 25, 10, 5);

const trimmedImageData = trimCanvas(canvas);

expect(trimmedImageData.width).toEqual(10);
expect(trimmedImageData.height).toEqual(5);
expect(trimmedImageData.width).toEqual(15);
expect(trimmedImageData.height).toEqual(10);
expect(trimmedImageData.data).toBeInstanceOf(ImageData);
expect(trimmedImageData.data.width).toEqual(15);
expect(trimmedImageData.data.height).toEqual(10);
expect(trimmedImageData.data.data).toEqual(context.getImageData(10, 20, 15, 10).data);
});
});

0 comments on commit 3de5609

Please sign in to comment.