import React, { useState, useEffect } from 'react';
import ReactDOMServer from 'react-dom/server';
function extractColorsFromImage(imageUrl) {
const img = new Image();
img.crossOrigin = 'Anonymous';
img.src = imageUrl;
return new Promise((resolve, reject) => {
img.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const pixels = imageData.data;
const colors = new Set();
for (let i = 0; i < pixels.length; i += 4) {
const r = pixels[i];
const g = pixels[i + 1];
const b = pixels[i + 2];
const a = pixels[i + 3];
if (a === 0) {
continue;
}
const color = `rgba(${r}, ${g}, ${b}, ${a})`;
colors.add(color);
}
resolve(Array.from(colors));
};
img.onerror = reject;
});
}
const ImageColors = ({ imageUrl }) => {
const [colors, setColors] = useState([]);
useEffect(() => {
extractColorsFromImage(imageUrl).then(setColors);
}, [imageUrl]);
return (
<div>
{colors.map((color) => (
<div key={color} style={{ backgroundColor: color, width: 50, height: 50 }} />
))}
</div>
);
};
const html = ReactDOMServer.renderToString(<ImageColors imageUrl="https://example.com/image.png" />);
console.log(html);
在React 18中提取图片中的颜色需要使用第三方库,如color-thief或node-vibrant。
color-thief是一个用于提取图片中主要颜色的JavaScript库,可以在React 18项目中使用。首先,需要在项目中安装color-thief库:
npm install color-thief
然后,可以在React组件中引入color-thief并使用它来提取图片的颜色:
```javascript
import React, { useState, useEffect } from 'react';
import ColorThief from 'color-thief';
const MyComponent = () => {
const [color, setColor] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = () => {
const colorThief = new ColorThief();
const [r, g, b] = colorThief.getColor(img);
setColor(`rgb(${r}, ${g}, ${b})`);
setLoading(false);
};
img.src = 'path/to/image';
}, []);
return (
<>
{loading ? (
<p>Loading...</p>
) : (
<div style={{ backgroundColor: color }}>
<h1>My Component</h1>
</div>
)}
</>
);
};
export default MyComponent;
这样,就可以在React 18项目中提取图片中的颜色了。