我正在努力在反应应用程序中添加 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;
使用 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);
}}
/>
( 请注意,图像道具应该按照这个确切的顺序)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)