我正在努力在React应用程序中添加Color Thief。我已经按照github上的说明进行了操作,但是没有任何变化。 我已经应用了建议报告者here,然后将脚本插入到setTimeout函数中,但是总是收到相同的错误:
您能帮助我在响应中运行该库(如果有替代方案,请运行类似的库)?
到目前为止,这是我的代码:
import React from 'react';
import './App.css';
var ColorThief = require('color-thief');
function App() {
setTimeout(function(){
var colorThief = new ColorThief();
var img = 'img.jpg';
var palette = colorThief.getPalette(img, 8);
var dominant = colorThief.getColor(img);
console.log(palette);
console.log(dominant);
document.getElementById("app").style.backgroundColor = "rgb(" + dominant + ")";
}, 3000);
return (
<div id="app"></div>
);
}
export default App;
答案 0 :(得分:0)
使用npm安装库:
$ npm i --save colorthief
将库导入文件中为:
import ColorThief from "colorthief";
为图像创建反应引用,如下所示:
constructor(props) {
super(props);
// Image element reference
this.imgRef = React.createRef();
}
图像组件应如下所示:
<img
crossOrigin={"anonymous"}
ref={this.imgRef}
src={
"https://images.unsplash.com/photo-1516876437184-593fda40c7ce"
}
alt={"example"}
className={"example__img"}
onLoad={() => {
const colorThief = new ColorThief();
const img = this.imgRef.current;
const result = colorThief.getColor(img, 25);
}}
/>
(请注意,图片道具应与此完全相同)
答案 1 :(得分:0)
import ColorThief from "colorthief";
import _ from 'lodash';
export const getPalette = (url) => {
return new Promise((resolve, reject) => {
if (!url) {
reject();
}
const image = new Image();
image.src = url;
image.crossOrigin = 'Anonymous';
image.onload = function () {
const colorThief = new ColorThief();
const palette = colorThief.getPalette(this, 10);
const result = _.uniq(palette, item => JSON.stringify(item));
resolve(result);
}
});
}