inpainting-canvas.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. 'use client';
  2. import { useRef, useEffect, useState, useCallback } from 'react';
  3. import { Button } from '@/components/ui/button';
  4. import { Card, CardContent } from '@/components/ui/card';
  5. import { Label } from '@/components/ui/label';
  6. import { Upload, Download, Eraser, Brush, RotateCcw } from 'lucide-react';
  7. import { fileToBase64 } from '@/lib/utils';
  8. interface InpaintingCanvasProps {
  9. onSourceImageChange: (image: string) => void;
  10. onMaskImageChange: (image: string) => void;
  11. className?: string;
  12. }
  13. export function InpaintingCanvas({
  14. onSourceImageChange,
  15. onMaskImageChange,
  16. className
  17. }: InpaintingCanvasProps) {
  18. const canvasRef = useRef<HTMLCanvasElement>(null);
  19. const maskCanvasRef = useRef<HTMLCanvasElement>(null); // Keep for mask generation
  20. const fileInputRef = useRef<HTMLInputElement>(null);
  21. const [sourceImage, setSourceImage] = useState<string | null>(null);
  22. const [isDrawing, setIsDrawing] = useState(false);
  23. const [brushSize, setBrushSize] = useState(20);
  24. const [isEraser, setIsEraser] = useState(false);
  25. const [canvasSize, setCanvasSize] = useState({ width: 512, height: 512 });
  26. // Initialize canvases
  27. useEffect(() => {
  28. const canvas = canvasRef.current;
  29. const maskCanvas = maskCanvasRef.current;
  30. if (!canvas || !maskCanvas) return;
  31. const ctx = canvas.getContext('2d');
  32. const maskCtx = maskCanvas.getContext('2d');
  33. if (!ctx || !maskCtx) return;
  34. // Set canvas size
  35. canvas.width = canvasSize.width;
  36. canvas.height = canvasSize.height;
  37. maskCanvas.width = canvasSize.width;
  38. maskCanvas.height = canvasSize.height;
  39. // Initialize mask canvas with black (no inpainting)
  40. maskCtx.fillStyle = 'black';
  41. maskCtx.fillRect(0, 0, canvasSize.width, canvasSize.height);
  42. // Update mask image
  43. updateMaskImage();
  44. }, [canvasSize]);
  45. const updateMaskImage = useCallback(() => {
  46. const maskCanvas = maskCanvasRef.current;
  47. if (!maskCanvas) return;
  48. const maskDataUrl = maskCanvas.toDataURL();
  49. onMaskImageChange(maskDataUrl);
  50. }, [onMaskImageChange]);
  51. const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
  52. const file = e.target.files?.[0];
  53. if (!file) return;
  54. try {
  55. const base64 = await fileToBase64(file);
  56. setSourceImage(base64);
  57. onSourceImageChange(base64);
  58. // Load image to get dimensions and update canvas size
  59. const img = new Image();
  60. img.onload = () => {
  61. // Calculate scaled dimensions to fit within 512x512 while maintaining aspect ratio
  62. const maxSize = 512;
  63. let width = img.width;
  64. let height = img.height;
  65. if (width > maxSize || height > maxSize) {
  66. const aspectRatio = width / height;
  67. if (width > height) {
  68. width = maxSize;
  69. height = maxSize / aspectRatio;
  70. } else {
  71. height = maxSize;
  72. width = maxSize * aspectRatio;
  73. }
  74. }
  75. const newCanvasSize = { width: Math.round(width), height: Math.round(height) };
  76. setCanvasSize(newCanvasSize);
  77. // Draw image on main canvas
  78. const canvas = canvasRef.current;
  79. if (!canvas) return;
  80. const ctx = canvas.getContext('2d');
  81. if (!ctx) return;
  82. canvas.width = width;
  83. canvas.height = height;
  84. ctx.drawImage(img, 0, 0, width, height);
  85. // Update mask canvas size
  86. const maskCanvas = maskCanvasRef.current;
  87. if (!maskCanvas) return;
  88. const maskCtx = maskCanvas.getContext('2d');
  89. if (!maskCtx) return;
  90. maskCanvas.width = width;
  91. maskCanvas.height = height;
  92. maskCtx.fillStyle = 'black';
  93. maskCtx.fillRect(0, 0, width, height);
  94. updateMaskImage();
  95. };
  96. img.src = base64;
  97. } catch (err) {
  98. console.error('Failed to load image:', err);
  99. }
  100. };
  101. const startDrawing = (e: React.MouseEvent<HTMLCanvasElement>) => {
  102. if (!sourceImage) return;
  103. setIsDrawing(true);
  104. draw(e);
  105. };
  106. const stopDrawing = () => {
  107. setIsDrawing(false);
  108. };
  109. const draw = (e: React.MouseEvent<HTMLCanvasElement>) => {
  110. if (!isDrawing || !sourceImage) return;
  111. const canvas = canvasRef.current;
  112. const maskCanvas = maskCanvasRef.current;
  113. if (!canvas || !maskCanvas) return;
  114. const ctx = canvas.getContext('2d');
  115. const maskCtx = maskCanvas.getContext('2d');
  116. if (!ctx || !maskCtx) return;
  117. const rect = canvas.getBoundingClientRect();
  118. const scaleX = canvas.width / rect.width;
  119. const scaleY = canvas.height / rect.height;
  120. const x = (e.clientX - rect.left) * scaleX;
  121. const y = (e.clientY - rect.top) * scaleY;
  122. // Draw on mask canvas (for API)
  123. maskCtx.globalCompositeOperation = 'source-over';
  124. maskCtx.fillStyle = isEraser ? 'black' : 'white';
  125. maskCtx.beginPath();
  126. maskCtx.arc(x, y, brushSize, 0, Math.PI * 2);
  127. maskCtx.fill();
  128. // Draw visual overlay directly on main canvas
  129. ctx.save();
  130. ctx.globalCompositeOperation = 'source-over';
  131. if (isEraser) {
  132. // For eraser, just redraw the image at that position
  133. const img = new Image();
  134. img.onload = () => {
  135. // Clear the area and redraw
  136. ctx.save();
  137. ctx.globalCompositeOperation = 'destination-out';
  138. ctx.beginPath();
  139. ctx.arc(x, y, brushSize, 0, Math.PI * 2);
  140. ctx.fill();
  141. ctx.restore();
  142. // Redraw the image in the cleared area
  143. ctx.save();
  144. ctx.globalCompositeOperation = 'destination-over';
  145. ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
  146. ctx.restore();
  147. updateMaskImage();
  148. };
  149. img.src = sourceImage;
  150. } else {
  151. // For brush, draw a visible overlay
  152. ctx.globalAlpha = 0.6;
  153. ctx.fillStyle = 'rgba(255, 105, 180, 0.8)'; // Bright pink for visibility
  154. ctx.beginPath();
  155. ctx.arc(x, y, brushSize, 0, Math.PI * 2);
  156. ctx.fill();
  157. // Also draw a border for better visibility
  158. ctx.globalAlpha = 1.0;
  159. ctx.strokeStyle = 'rgba(255, 0, 0, 0.9)'; // Red border
  160. ctx.lineWidth = 2;
  161. ctx.beginPath();
  162. ctx.arc(x, y, brushSize, 0, Math.PI * 2);
  163. ctx.stroke();
  164. ctx.restore();
  165. updateMaskImage();
  166. }
  167. };
  168. const clearMask = () => {
  169. const canvas = canvasRef.current;
  170. const maskCanvas = maskCanvasRef.current;
  171. if (!canvas || !maskCanvas) return;
  172. const ctx = canvas.getContext('2d');
  173. const maskCtx = maskCanvas.getContext('2d');
  174. if (!ctx || !maskCtx) return;
  175. // Clear mask canvas
  176. maskCtx.fillStyle = 'black';
  177. maskCtx.fillRect(0, 0, maskCanvas.width, maskCanvas.height);
  178. // Redraw source image on main canvas
  179. if (sourceImage) {
  180. const img = new Image();
  181. img.onload = () => {
  182. ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
  183. };
  184. img.src = sourceImage;
  185. }
  186. updateMaskImage();
  187. };
  188. const downloadMask = () => {
  189. const canvas = maskCanvasRef.current;
  190. if (!canvas) return;
  191. const link = document.createElement('a');
  192. link.download = 'inpainting-mask.png';
  193. link.href = canvas.toDataURL();
  194. link.click();
  195. };
  196. return (
  197. <div className={`space-y-4 ${className}`}>
  198. <Card>
  199. <CardContent className="pt-6">
  200. <div className="space-y-4">
  201. <div className="space-y-2">
  202. <Label>Source Image</Label>
  203. <div className="space-y-4">
  204. <Button
  205. type="button"
  206. variant="outline"
  207. onClick={() => fileInputRef.current?.click()}
  208. className="w-full"
  209. >
  210. <Upload className="h-4 w-4 mr-2" />
  211. {sourceImage ? 'Change Image' : 'Upload Image'}
  212. </Button>
  213. <input
  214. ref={fileInputRef}
  215. type="file"
  216. accept="image/*"
  217. onChange={handleImageUpload}
  218. className="hidden"
  219. />
  220. </div>
  221. </div>
  222. {sourceImage && (
  223. <>
  224. <div className="space-y-2">
  225. <Label>Mask Editor</Label>
  226. <div className="relative">
  227. <canvas
  228. ref={canvasRef}
  229. className="rounded-lg border border-border cursor-crosshair"
  230. style={{ maxWidth: '512px', height: 'auto' }}
  231. onMouseDown={startDrawing}
  232. onMouseUp={stopDrawing}
  233. onMouseMove={draw}
  234. onMouseLeave={stopDrawing}
  235. />
  236. </div>
  237. <p className="text-xs text-muted-foreground">
  238. Draw on the image to mark areas for inpainting. White areas will be inpainted, black areas will be preserved.
  239. </p>
  240. </div>
  241. <div className="space-y-2">
  242. <Label htmlFor="brush_size">
  243. Brush Size: {brushSize}px
  244. </Label>
  245. <input
  246. id="brush_size"
  247. type="range"
  248. value={brushSize}
  249. onChange={(e) => setBrushSize(Number(e.target.value))}
  250. min={1}
  251. max={100}
  252. className="w-full"
  253. />
  254. </div>
  255. <div className="flex gap-2">
  256. <Button
  257. type="button"
  258. variant={isEraser ? "default" : "outline"}
  259. onClick={() => setIsEraser(true)}
  260. className="flex-1"
  261. >
  262. <Eraser className="h-4 w-4 mr-2" />
  263. Eraser
  264. </Button>
  265. <Button
  266. type="button"
  267. variant={!isEraser ? "default" : "outline"}
  268. onClick={() => setIsEraser(false)}
  269. className="flex-1"
  270. >
  271. <Brush className="h-4 w-4 mr-2" />
  272. Brush
  273. </Button>
  274. </div>
  275. <div className="flex gap-2">
  276. <Button
  277. type="button"
  278. variant="outline"
  279. onClick={clearMask}
  280. className="flex-1"
  281. >
  282. <RotateCcw className="h-4 w-4 mr-2" />
  283. Clear Mask
  284. </Button>
  285. <Button
  286. type="button"
  287. variant="outline"
  288. onClick={downloadMask}
  289. className="flex-1"
  290. >
  291. <Download className="h-4 w-4 mr-2" />
  292. Download Mask
  293. </Button>
  294. </div>
  295. </>
  296. )}
  297. </div>
  298. </CardContent>
  299. </Card>
  300. </div>
  301. );
  302. }