| 1 | - mode: both |
| 2 | + mode: canvas |
main.js
· 1.4 KiB · JavaScript
Brut
// Canvas 前端取色
const getColorByCanvas = (img) => {
return new Promise((resolve, reject) => {
try {
img.crossOrigin = "Anonymous";
const extract = () => {
try {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
canvas.width = 1; canvas.height = 1;
ctx.drawImage(img, 0, 0, 1, 1);
const [r, g, b] = ctx.getImageData(0, 0, 1, 1).data;
resolve(`#${r.toString(16).padStart(2,"0")}${g.toString(16).padStart(2,"0")}${b.toString(16).padStart(2,"0")}`);
} catch (e) { reject(e); }
};
if (img.complete) extract();
else { img.addEventListener("load", extract, { once: true }); img.addEventListener("error", () => reject(new Error("img load failed")), { once: true }); }
} catch (e) { reject(e); }
});
};
// 应用取色结果
const applyColor = (value) => {
if (getContrastYIQ(value) === "light") value = LightenDarkenColor(colorHex(value), -40);
root.style.setProperty("--anzhiyu-bar-background", value);
requestAnimationFrame(() => anzhiyu.initThemeColor());
if (GLOBAL_CONFIG.mainTone.cover_change) {
document.documentElement.style.setProperty("--anzhiyu-main", value);
document.documentElement.style.setProperty("--anzhiyu-theme-op", value + "23");
document.documentElement.style.setProperty("--anzhiyu-theme-op-deep", value + "dd");
}
};
| 1 | // Canvas 前端取色 |
| 2 | const getColorByCanvas = (img) => { |
| 3 | return new Promise((resolve, reject) => { |
| 4 | try { |
| 5 | img.crossOrigin = "Anonymous"; |
| 6 | const extract = () => { |
| 7 | try { |
| 8 | const canvas = document.createElement("canvas"); |
| 9 | const ctx = canvas.getContext("2d"); |
| 10 | canvas.width = 1; canvas.height = 1; |
| 11 | ctx.drawImage(img, 0, 0, 1, 1); |
| 12 | const [r, g, b] = ctx.getImageData(0, 0, 1, 1).data; |
| 13 | resolve(`#${r.toString(16).padStart(2,"0")}${g.toString(16).padStart(2,"0")}${b.toString(16).padStart(2,"0")}`); |
| 14 | } catch (e) { reject(e); } |
| 15 | }; |
| 16 | if (img.complete) extract(); |
| 17 | else { img.addEventListener("load", extract, { once: true }); img.addEventListener("error", () => reject(new Error("img load failed")), { once: true }); } |
| 18 | } catch (e) { reject(e); } |
| 19 | }); |
| 20 | }; |
| 21 | |
| 22 | // 应用取色结果 |
| 23 | const applyColor = (value) => { |
| 24 | if (getContrastYIQ(value) === "light") value = LightenDarkenColor(colorHex(value), -40); |
| 25 | root.style.setProperty("--anzhiyu-bar-background", value); |
| 26 | requestAnimationFrame(() => anzhiyu.initThemeColor()); |
| 27 | if (GLOBAL_CONFIG.mainTone.cover_change) { |
| 28 | document.documentElement.style.setProperty("--anzhiyu-main", value); |
| 29 | document.documentElement.style.setProperty("--anzhiyu-theme-op", value + "23"); |
| 30 | document.documentElement.style.setProperty("--anzhiyu-theme-op-deep", value + "dd"); |
| 31 | } |
| 32 | }; |