依赖于 rgbaster 包,
安装rgbaster: yarn add rgbaster
import analyze from 'rgbaster'
export default {
mounted() {
this.getBackground()
},
methods: {
getBackground() {
const that = this
function getBase64Image(img, suffix) {
let 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 dataURL = canvas.toDataURL('image/' + suffix) // 可选其他值 image/jpeg
canvas = null // 释放
return dataURL
}
function getColors(src, cb) {
const image = new Image()
const splits = src.split('.')
const suffix = splits[splits.length - 1]
image.setAttribute('crossOrigin', 'anonymous') // 支持跨域图片
image.src = src + '?v=' + Math.random() // 处理缓存
image.onload = function () {
const base64 = getBase64Image(image, suffix)
cb && cb(base64)
}
}
getColors('https://cdn.bg7zag.com/wp-content/uploads/2019/04/zh-2.jpg', async function (base64) {
const result = await analyze(base64, { scale: 0.6 }) // also supports base64 encoded image strings
that.bgColor = result[0].color
})
}
}
}
部分内容来着:canvas图片问题浅析、JS将图片转为base64编码
学习了,顺便推荐一下我们平台——火投票