Skip to content

Commit dddb5ca

Browse files
committed
feat: canvas auto clean cache
1 parent 41bdf57 commit dddb5ca

File tree

2 files changed

+11
-5
lines changed

2 files changed

+11
-5
lines changed

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "zhiwen-img-compress",
33
"private": false,
4-
"version": "0.0.3",
4+
"version": "0.0.6",
55
"main": "dist/index.js",
66
"module": "dist/index.js",
77
"types": "dist/index.d.ts",

src/compress.ts

+10-4
Original file line numberDiff line numberDiff line change
@@ -54,17 +54,23 @@ export async function compressImg(file: Blob, options?: CompressOptions): Promis
5454
scale = Math.min(Math.sqrt(MaxArea / area), mLen / width, mLen / height);
5555
}
5656

57+
width = Math.floor(width * scale);
58+
height = Math.floor(height * scale);
59+
const canvas = new OffscreenCanvas(1, 1);
60+
5761
let blob: Blob;
5862
do {
59-
width = Math.floor(width * scale);
60-
height = Math.floor(height * scale);
61-
const canvas = new OffscreenCanvas(width, height);
63+
canvas.width = width = Math.floor(width * scale);
64+
canvas.height = height = Math.floor(height * scale);
6265
const ctx = canvas.getContext("2d")!;
6366
ctx.scale(scale, scale);
6467
ctx.drawImage(bitmap, 0, 0);
6568
blob = await canvas.convertToBlob({ type, quality });
6669
// bold size 越大,质量越差
6770
scale *= Math.sqrt(mSize / blob.size);
68-
} while (blob.size > mSize && quality > 0.1);
71+
} while (blob.size > mSize);
72+
bitmap.close();
73+
canvas.width = 0;
74+
canvas.height = 0;
6975
return blob;
7076
}

0 commit comments

Comments
 (0)