官网:
npm i --save colorthief
第一种,import载入图片
经过尝试,在vite中,要引入.mjs版本
import ColorThief from 'colorthief/dist/color-thief.mjs'
第一种,通过import载入图片
import aa from '@/assets/123.jpg'
const [resultColor,setResultColor]=useState('')
useEffect(()=>{
var colorthief = new ColorThief();
var img = document.getElementById('tupian')
if (img.complete) {
var res = colorthief.getColor(img);
console.log('======网速很快', res);
setResultColor(res)
} else {
img.addEventListener('load', function () {
var res = colorthief.getColor(img)
console.log('======事件监听', res);
setResultColor(res)
});
}
},[])
<img src={aa} id="tupian" />
<div style={{ width: '100px', height: '100px', backgroundColor: `rgba(${resultColor})` }}></div>
第二种,new Image实例
经过尝试,在vite中,要引入.mjs版本
import ColorThief from 'colorthief/dist/color-thief.mjs'
import aa from '@/assets/123.jpg'
const [resultColor,setResultColor]=useState('')
useEffect(()=>{
var colorthief = new ColorThief();
var img = new Image()
img.src = '/123.jpg'
if (img.complete) {
var res = colorthief.getColor(img);
console.log('======网速很快', res);
setResultColor(res)
} else {
img.addEventListener('load', function () {
var res = colorthief.getColor(img)
console.log('======事件监听', res);
setResultColor(res)
});
}
},[])
<img src={aa} id="tupian" />
<div style={{ width: '100px', height: '100px', backgroundColor: `rgba(${resultColor})` }}></div>
图片如果设计跨域,那么需要在img标签上增加crossorigin,同时对应的图片服务器也要增加允许跨域,缺一不可.
附赠2个常用函数
export default function imgToBase64(url) {
return new Promise((resolve, reject) => {
const image = new Image()
image.src = url
image.onload = () => {
const canvas = document.createElement('canvas')
canvas.width = image.naturalWidth // 使用 naturalWidth 为了保证图片的清晰度
canvas.height = image.naturalHeight
canvas.style.width = `${canvas.width / window.devicePixelRatio}px`
canvas.style.height = `${canvas.height / window.devicePixelRatio}px`
const ctx = canvas.getContext('2d')
if (!ctx) {
return null
}
ctx.drawImage(image, 0, 0)
const base64 = canvas.toDataURL('image/png')
return resolve(base64)
}
image.onerror = (err) => {
return reject(err);
}
})
}
export function getURLBase64(url) {
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest()
xhr.open('get', url, true)
xhr.responseType = 'blob'
xhr.onload = function () {
if (this.status === 200) {
var blob = this.response
var fileReader = new FileReader()
fileReader.onloadend = function (e) {
var result = e.target.result
resolve(result)
}
fileReader.readAsDataURL(blob)
}
}
xhr.onerror = function () {
reject()
}
xhr.send()
})
}