Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[bug fix] Clear unused canvases to avoid memory leak. #191

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions lib/image-compression.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,9 @@ export default async function compress(file, options, previousProgress = 0) {
if (process.env.BUILD === 'development') {
console.log('no need to compress');
}
cleanupCanvasMemory(maxWidthOrHeightFixedCanvas);
cleanupCanvasMemory(orientationFixedCanvas);
cleanupCanvasMemory(origCanvas);
setProgress(100);
return tempFile;
}
Expand Down
10 changes: 6 additions & 4 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -292,9 +292,11 @@ export function cleanupCanvasMemory(canvas) {
// garbage clean canvas for safari
// ref: https://bugs.webkit.org/show_bug.cgi?id=195325
// eslint-disable-next-line no-param-reassign
canvas.width = 0;
canvas.width = 1;
// eslint-disable-next-line no-param-reassign
canvas.height = 0;
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Setting the width or height to 0 doesn't actually free up memory. Instead, it makes the canvas context unavailable to the canvas, while the associated pixel data remains preserved in memory. The correct method for clearing memory is to set the size to 1.

Refer to this blog post for more information: https://pqina.nl/blog/total-canvas-memory-use-exceeds-the-maximum-limit/

canvas.height = 1;
const ctx = canvas.getContext('2d');
ctx && ctx.clearRect(0, 0, 1, 1);
}

// Check if browser supports automatic image orientation
Expand All @@ -315,8 +317,8 @@ export async function isAutoOrientationInBrowser() {
const testImageCanvas = (await drawFileInCanvas(testImageFile))[1];
const testImageFile2 = await canvasToFile(testImageCanvas, testImageFile.type, testImageFile.name, testImageFile.lastModified);
cleanupCanvasMemory(testImageCanvas);
const img = (await drawFileInCanvas(testImageFile2))[0];
// console.log('img', img.width, img.height)
const [img, fileCanvas] = (await drawFileInCanvas(testImageFile2));
cleanupCanvasMemory(fileCanvas);

isAutoOrientationInBrowser.cachedResult = img.width === 1 && img.height === 2;
return isAutoOrientationInBrowser.cachedResult;
Expand Down