| 1 | - mode: both |
| 2 | + mode: canvas |
调用浏览器原生 Canvas API 在前端直接提取封面图主色调
Revision 2d540351c92f13d0840e0e93184a2c55fa56bd1e
| 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 | }; |