-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
66 lines (58 loc) · 2.22 KB
/
index.js
File metadata and controls
66 lines (58 loc) · 2.22 KB
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
const imageObjects = [null, null, null, null, null, null];
window.onload = _ => {
const canvas = document.getElementById('mainCanvas');
const canvasContainer = document.querySelector('.canvas-container');
for (let i = 1; i <= 5; i++) {
const imageBox = document.getElementById(`imageBox${i}`);
const fileInput = document.getElementById(`fileInput${i}`);
imageBox.addEventListener('click', () => {
fileInput.click();
});
fileInput.addEventListener('change', (e) => {
const file = e.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = (event) => {
const uploadText = imageBox.querySelector('.upload-text');
if (uploadText) imageBox.removeChild(uploadText);
const existingImg = imageBox.querySelector('img');
if (existingImg) imageBox.removeChild(existingImg);
const img = new Image();
img.src = event.target.result;
img.crossOrigin = 'anonymous';
img.onload = () => {
imageBox.appendChild(img);
imageObjects[i] = img;
let width = imageObjects[1] ? imageObjects[1].naturalWidth : 0
canvas.width = canvas.height = width * 8
render(width, imageObjects, canvas.getContext('2d'));
};
};
reader.readAsDataURL(file);
}
});
}
const resizeCanvas = _ => {
const rect = canvasContainer.getBoundingClientRect();
const dpr = window.devicePixelRatio || 1;
canvas.width = rect.width * dpr;
canvas.height = rect.height * dpr;
canvas.style.width = `${rect.width}px`;
canvas.style.height = `${rect.height}px`;
const ctx = canvas.getContext('2d');
ctx.scale(dpr, dpr);
}
const downloadCanvas = _ => {
let filename = Date.now() + '.png'
let imgdata = canvas.toDataURL()
let link = document.createElement('a')
link.href = imgdata
link.download = filename
let event = document.createEvent('MouseEvents')
event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
link.dispatchEvent(event)
}
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
canvas.addEventListener('click', downloadCanvas)
}