利用 canvas 获取图片颜色,可获取图片主色与次色,并提供生成渐变效果API。
Obtain the main color and secondary color of the image, and provide the API for generating the gradient effect.
const imgs = Array.from(document.querySelectorAll('.img img'))
/** ============ 渐变 ===================== */
const famousImgs = imgs.slice(0, 8)
const famousImgSrc = famousImgs.map(img => img.src)
famousImgSrc.forEach((src,index) => {
const obj = colorGrade(src)
obj.getRenderGradient().then(rgba => {
famousImgs[index].parentNode.setAttribute('style', rgba)
})
})
/** =========== 调色板 ====================== */
const paletteImgs = imgs.slice(8, 16)
const paletteImgSrc = paletteImgs.map(img => img.src)
const paletteEls = Array.from(document.querySelectorAll('.example-palette .img .palette'))
paletteImgSrc.forEach((src,index) => {
const obj = colorGrade(src)
obj.getColor(5).then(color => {
const html = color.palette.map(o => {
// return some html
}).join('')
paletteEls[index] && (paletteEls[index].innerHTML = html)
})
})
# yarn
yarn add img-color-grade
# npm
npm install --save img-color-grade
从图像获取主色。颜色以三个表示红色,绿色和蓝色值的 RGB(A) 格式的字符串。
从图像获取排序的颜色,将两端的颜色与 background-image 拼接成 CSS 字符串。