console
const colorThief = new ColorThief();
const img = document.getElementById("demoImg");
const bgWrapper = document.getElementById("bg");
console.log("img", img);
let result = [];
let pResult = [];
if (img.complete) {
result = colorThief.getColor(img, 15);
pResult = colorThief.getPalette(img, 15);
changeBgScence();
} else {
img.addEventListener("load", function () {
result = colorThief.getColor(img, 15);
pResult = colorThief.getPalette(img, 15);
changeBgScence();
});
}
console.log("result", result);
console.log("pResult", pResult);
const rgbToHex = (r, g, b) =>
"#" +
[r, g, b]
.map((x) => {
const hex = x.toString(16);
return hex.length === 1 ? "0" + hex : hex;
})
.join("");
function changeBgScence() {
console.log('chagne sence')
bgWrapper.style.background = `rgb(${result[0]}, ${result[1]}, ${result[2]})`;
bgWrapper.style.background = `linear-gradient(90deg, rgba(${result[0]}, ${result[1]}, ${result[2]},1) 20%, rgba(255,255,255,0) 80%)`;
}
const btn = document.getElementById("changeImage");
const imgIpt = document.getElementById("imgsrc");
btn.addEventListener("click", function () {
const imgSrc = imgIpt.value;
img.src = imgSrc;
img.onload = function() {
result = colorThief.getColor(img, 15);
pResult = colorThief.getPalette(img, 15);
changeBgScence();
}
});
<div class="wrapper">
<div id="bg" class="bg"></div>
<img id="demoImg" src="https://lokeshdhakar.com/projects/color-thief/image-3.919e184e.jpg" alt="">
</div>
<div>
<input id="imgsrc" value="" />
<button id="changeImage">替换图片</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/color-thief/2.3.0/color-thief.umd.js"></script>
html,
body {
padding: 0;
border: 0;
margin: 0;
height: 100%;
width: 100%;
}
.wrapper {
width: 100%;
position: relative;
height: 500px;
}
#demoImg {
height: 100%;
width: 80%;
float: right;
}
.bg {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
opacity: 1;
}