import React, { useState, useRef, useEffect } from 'react';
// import './ColorRemovalComponent.css';
interface ColorRemovalComponentProps {}
const ColorRemovalComponent: React.FC<ColorRemovalComponentProps> = () => {
const [selectedImage, setSelectedImage] = useState<File | null>(null);
const [processedImageData, setProcessedImageData] = useState<string | null>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const [clickedColor, setClickedColor] = useState<string>('');
const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (file) {
setSelectedImage(file);
}
};
useEffect(() => {
if (selectedImage && canvasRef.current) {
const canvas = canvasRef.current;
const ctx = canvas.getContext('2d');
if (!ctx) {
console.error('无法获取 2D 绘图上下文');
return;
}
const image = new Image();
image.src = URL.createObjectURL(selectedImage);
image.onload = () => {
canvas.width = image.width;
canvas.height = image.height;
ctx.drawImage(image, 0, 0);
};
}
}, [selectedImage]);
const handleCanvasClick = (e: React.MouseEvent<HTMLCanvasElement>) => {
if (canvasRef.current) {
const canvas = canvasRef.current;
const ctx = canvas.getContext('2d');
if (!ctx) {
console.error('无法获取 2D 绘图上下文');
return;
}
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
const pixelData = ctx.getImageData(x, y, 1, 1).data;
const color = `rgba(${pixelData[0]}, ${pixelData[1]}, ${pixelData[2]}, ${pixelData[3] / 255})`;
setClickedColor(color);
}
};
const simulateColorRemoval = () => {
if (selectedImage && canvasRef.current && clickedColor) {
const canvas = canvasRef.current;
const ctx = canvas.getContext('2d');
if (!ctx) {
console.error('无法获取 2D 绘图上下文');
return;
}
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const data = imageData.data;
for (let i = 0; i < data.length; i += 4) {
const currentColor = `rgba(${data[i]}, ${data[i + 1]}, ${data[i + 2]}, ${data[i + 3] / 255})`;
if (currentColor === clickedColor) {
data[i] = 0;
data[i + 1] = 0;
data[i + 2] = 0;
data[i + 3] = 0;
}
}
ctx.putImageData(imageData, 0, 0);
const dataURL = canvas.toDataURL();
setProcessedImageData(dataURL);
}
};
return (
<div>
<input type="file" onChange={handleImageChange} />
<canvas ref={canvasRef} onClick={handleCanvasClick}></canvas>
<button onClick={simulateColorRemoval}>删除点击颜色</button>
{/* {processedImageData && <img src={processedImageData} alt="Processed" />} */}
</div>
);
};
export default ColorRemovalComponent;