js实现图片主色调检测及更换背景色的5种方式colorThief colorify Vibrant daptive-backgrounds加原生
开发中产品可能提这样的需求,网页幻灯片中背景色会根据当前图片的主色调进行动态更换,达到一定的美感,这个有点类似手机桌面主题根据手机壳颜色更换的那个需求(已经跟产品干起来了),今天不用跟产品吵起来,有5种实现方式呢。
一、colorThief
colorThief是一个非常有用且易于使用的插件,用于从图像中获取调色板。它的画布标签使它发生。如果使用已加载到DOM中的图像,则可以同步检索颜色调色板。<script type="text/javascript"> const colorThief = new ColorThief(); const imgs = document.getElementById('imgs'); // Make sure image is finished loading if (imgs.complete) { console.log(colorThief.getColor(imgs)); } else { imgs.addEventListener('load', function() { let color = colorThief.getColor(imgs); var span = document.getElementById('span'); span.style.background = "rgb(" +color[0] + "," + color[1]+ "," + color[2] + ")" }); } </script>demo查看 http://editor.bfw.wiki/Editor/Open.html?projectid=15748222447089740088&file=demo1.html
二、colorify
使用 Colorify.js,,你可以:<script type="text/javascript"> const imgs = document.getElementById('imgs'); // Make sure image is finished loading if (imgs.complete) { console.log(colorThief.getColor(imgs)); } else { imgs.addEventListener('load', function() { colorify({ id: 1, container: 'colorify', images: false, accuracy: 100, gradient: false, gradientDirection: false, padding: 10, lazyReveal: false, give: false, revealOn: false }); var span = document.get...
点击查看剩余70%
网友评论0