const pixelData = context.getImageData(0, 0, canvas.width, canvas.height).data as any as number[]
// 获取 rgba 像素点的数据和出现的次数并排序
function getPrimaryColor (pixelData: number[]) {
const rgba = [] as (number | undefined)[]
for (let i = 0; i < pixelData.length; i += 4) {
rgba[1] = pixelData[i + 1]
rgba[2] = pixelData[i + 2]
rgba[3] = pixelData[i + 3]
if (rgba.includes(undefined) || pixelData[i + 3] === 0) {
if (rgbaStr in colorList) {
const arr = [] as { color: string, count: number }[]
for (const prop in colorList) {
// 如果只获取rgb,则为`rgb(${prop})`
function resolveImage (): Promise<number[]> {
return new Promise((resolve, reject) => {
const canvas = document.createElement('canvas')
const img = new Image() // 创建img元素
img.src = imageSrc // 设置图片源地址
resolve(getImagePixelData(canvas, img))
return getPrimaryColor(await resolveImage())
console.log(getImagePrimaryColor("./test.jpeg"))