/**
* 获取图片主元素
* @param img 图片dom
* @param callback 回调函数
*/
function getMainColor(img: HTMLImageElement, callback: any) {
//允许图片链接跨源
img.crossOrigin = ''
//图片加载
img.onload = function () {
//创建canvas元素
const canvas = document.createElement('canvas')
canvas.width = img.width
canvas.height = img.height
//获取二维画布
const ctx = canvas.getContext('2d')
//画布绘制图片
ctx?.drawImage(img, 0, 0, img.width, img.height)
//获取图片信息
const imageData = ctx?.getImageData(0, 0, img.width, img.height)
//图片颜色参数:为 r g b a
const pixels = imageData?.data
let mainColor = ''
let r = 0
let g = 0
let b = 0
let cnt = 0
if (pixels) {
for (let i = 0; i < pixels.length; i += 4) {
r += pixels[i]
g += pixels[i + 1]
b += pixels[i + 2]
cnt++
}
}
const _r = Math.abs(r / cnt - 255)
const _g = Math.abs(g / cnt - 255)
const _b = Math.abs(b / cnt - 255)
// console.log(_r, _g, _b)
if (_r < _g) {
if (_r < _b) {
mainColor = `rgb(255,${filterColor((g / cnt) * 0.3)},${(b / cnt) * 0.3})`
} else {
mainColor = `rgb(${(r / cnt) * 0.3},${filterColor((g / cnt) * 0.3)},255)`
}
} else {
if (_g < _b) {
mainColor = `rgb(${(r / cnt) * 0.3},255,${(b / cnt) * 0.3})`
} else {
mainColor = `rgb(${(r / cnt) * 0.3},${filterColor((g / cnt) * 0.3)},255)`
}
}
callback(`rgb(${(r / cnt) * 0.9},${(g / cnt) * 0.9},${(b / cnt) * 0.9},0.2)`, mainColor)
}
}
可以自己过滤一些自己不喜欢或者不需要的颜色,最后通过回调函数传回去