-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
99 lines (83 loc) · 2.79 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import * as iq from "image-q";
function padTime(number) {
return number < 10 ? "0" + number : number;
}
function getTime() {
const now = new Date();
return (
padTime(now.getHours()) +
":" +
padTime(now.getMinutes()) +
":" +
padTime(now.getSeconds()) +
"." +
now.getMilliseconds()
);
}
setInterval(function () {
document.getElementById("time").innerText = getTime();
}, 50);
function setPalette(points) {
points.forEach(function (point, index) {
document.getElementById("color-" + index).style.backgroundColor =
"rgb(" + point.r + "," + point.g + "," + point.b + ")";
});
document.getElementById("loader-wrapper").style.display = "none";
document.getElementById("colors-wrapper").style.display = "block";
document.getElementById("image-link").style.display = "block";
}
let worker;
if (window.Worker) {
worker = new Worker("worker.js");
worker.onmessage = function (message) {
setPalette(message.data.points);
};
}
function handleError(message) {
const errorMessage = document.getElementById("error-message");
errorMessage.innerText = message;
errorMessage.style.display = "block";
document.getElementById("loader-wrapper").style.display = "none";
document.getElementById("image-link").style.display = "none";
}
document
.getElementById("image-url-form")
.addEventListener("submit", function (event) {
event.preventDefault();
const url = event.target.elements.url.value;
const image = document.getElementById("image");
image.onload = function () {
document.getElementById("image-link").href = url;
const canvas = document.createElement("canvas");
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
const context = canvas.getContext("2d");
context.drawImage(image, 0, 0);
const imageData = context.getImageData(
0,
0,
image.naturalWidth,
image.naturalHeight
);
if (event.target.elements.worker.checked) {
if (worker) {
worker.postMessage({ imageData });
} else {
handleError("Your browser doesn't support Web Workers.");
}
return;
}
const pointContainer = iq.utils.PointContainer.fromImageData(imageData);
const palette = iq.buildPaletteSync([pointContainer], { colors: 4 });
const points = palette._pointArray;
setPalette(points);
};
image.onerror = function () {
handleError("The image failed to load. Please double check the URL.");
};
document.getElementById("error-message").style.display = "none";
document.getElementById("loader-wrapper").style.display = "block";
document.getElementById("colors-wrapper").style.display = "none";
document.getElementById("image-link").style.display = "none";
image.src = url;
});