-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
46 lines (34 loc) · 1.59 KB
/
index.js
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
function fillImageWithBlur(e, canvasId) {
const canvas = document.getElementById(canvasId);
const ctx = canvas.getContext('2d');
const downloadLink = document.createElement('a');
const image = new Image();
image.src = URL.createObjectURL(e.target.files[0]);
image.onload = function () {
const aspectRatio = canvas.width / canvas.height;
const imageAspectRatio = image.width / image.height;
let newWidth, newHeight;
if (imageAspectRatio > aspectRatio) {
newWidth = canvas.width;
newHeight = canvas.width / imageAspectRatio;
} else {
newWidth = canvas.height * imageAspectRatio;
newHeight = canvas.height;
}
const xOffset = (canvas.width - newWidth) / 2;
const yOffset = (canvas.height - newHeight) / 2;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.filter = 'blur(50px)';
ctx.drawImage(image, -100, -100, canvas.width + 200, canvas.height + 200);
ctx.filter = 'none';
ctx.drawImage(image, xOffset, yOffset, newWidth, newHeight);
const originalExtension = e.target.files[0].name.split('.').pop();
const fileNameWithoutExtension = e.target.files[0].name.replace(/\.[^/.]+$/, '');
downloadLink.href = canvas.toDataURL(`image/${originalExtension}`);
downloadLink.download = `${fileNameWithoutExtension}_blurred.${originalExtension}`;
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
};
}
module.export = fillImageWithBlur