我正在努力在react应用程序中添加Color Thief。我已经按照github上的说明进行了操作,但没有任何变化。我已经应用了建议报告here,然后在setTimeout函数中插入了脚本,但我总是得到相同的错误:

你能帮助我在react中运行这个库(如果你有其他选择的话,或者类似的库)吗?
到目前为止,我的代码如下:
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;发布于 2019-09-06 03:26:57
使用npm安装库:
$ npm i --save colorthief将库导入到文件中,如下所示:
import ColorThief from "colorthief";创建一个指向您的图像的react引用,如下所示:
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);
}}
/>(请注意,图像道具应该按照这个顺序)
发布于 2020-03-31 19:03:47
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);
}
});
}发布于 2022-01-28 07:28:27
下面的代码适用于我。版本: "colorthief":"^2.3.2",
import ColorThief from "../../../node_modules/colorthief/dist/color-thief.mjs"; // your node modules path
export const getPalette = (url) => {
return new Promise(resolve=>{
const img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = () => {
let colorThief = new ColorThief();
resolve(colorThief.getPalette(img));
}
img.src = url;
})
}https://stackoverflow.com/questions/56181633
复制相似问题