File size: 15,867 Bytes
921d377 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 | /**
* MaskCanvas - Canvas overlay component for drawing inpainting masks.
*
* Features:
* - Canvas overlay on top of the image
* - Brush drawing with adjustable size and opacity
* - Eraser mode
* - Undo/Redo support
* - Clear mask
* - Export mask as data URL
*/
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { resolveFileUrl } from '../resolveFileUrl';
import { Brush, Eraser, Undo2, Redo2, Trash2, Eye, EyeOff, Check, X, } from 'lucide-react';
export function MaskCanvas({ imageUrl, onSaveMask, onCancel, initialMask, }) {
const canvasRef = useRef(null);
const containerRef = useRef(null);
// Drawing state
const [isDrawing, setIsDrawing] = useState(false);
const [mode, setMode] = useState('brush');
const [brushSize, setBrushSize] = useState(30);
const [brushOpacity, setBrushOpacity] = useState(1.0);
const [showMask, setShowMask] = useState(true);
// History for undo/redo
const [history, setHistory] = useState([]);
const [historyIndex, setHistoryIndex] = useState(-1);
// Image dimensions
const [imageDimensions, setImageDimensions] = useState({ width: 0, height: 0 });
const [canvasScale, setCanvasScale] = useState(1);
// Initialize canvas when image loads
useEffect(() => {
const img = new Image();
img.crossOrigin = 'anonymous';
img.onload = () => {
const canvas = canvasRef.current;
const container = containerRef.current;
if (!canvas || !container)
return;
// Calculate scale to fit in container while maintaining aspect ratio
const maxWidth = container.clientWidth - 32;
const maxHeight = container.clientHeight - 32;
const scale = Math.min(maxWidth / img.width, maxHeight / img.height, 1);
const scaledWidth = Math.floor(img.width * scale);
const scaledHeight = Math.floor(img.height * scale);
// Set canvas to actual image dimensions for mask quality
canvas.width = img.width;
canvas.height = img.height;
// Store dimensions and scale
setImageDimensions({ width: img.width, height: img.height });
setCanvasScale(scale);
// Clear canvas with transparent background
const ctx = canvas.getContext('2d');
if (ctx) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Load initial mask if provided
if (initialMask) {
const maskImg = new Image();
maskImg.crossOrigin = 'anonymous';
maskImg.onload = () => {
ctx.drawImage(maskImg, 0, 0, canvas.width, canvas.height);
saveToHistory();
};
maskImg.src = initialMask;
}
else {
saveToHistory();
}
}
};
img.src = imageUrl;
}, [imageUrl, initialMask]);
// Save current canvas state to history
const saveToHistory = useCallback(() => {
const canvas = canvasRef.current;
if (!canvas)
return;
const ctx = canvas.getContext('2d');
if (!ctx)
return;
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
setHistory((prev) => {
// Remove any future history if we're not at the end
const newHistory = prev.slice(0, historyIndex + 1);
newHistory.push({ imageData });
// Limit history to 50 entries
if (newHistory.length > 50)
newHistory.shift();
return newHistory;
});
setHistoryIndex((prev) => Math.min(prev + 1, 49));
}, [historyIndex]);
// Undo
const handleUndo = useCallback(() => {
if (historyIndex <= 0)
return;
const canvas = canvasRef.current;
if (!canvas)
return;
const ctx = canvas.getContext('2d');
if (!ctx)
return;
const newIndex = historyIndex - 1;
setHistoryIndex(newIndex);
ctx.putImageData(history[newIndex].imageData, 0, 0);
}, [history, historyIndex]);
// Redo
const handleRedo = useCallback(() => {
if (historyIndex >= history.length - 1)
return;
const canvas = canvasRef.current;
if (!canvas)
return;
const ctx = canvas.getContext('2d');
if (!ctx)
return;
const newIndex = historyIndex + 1;
setHistoryIndex(newIndex);
ctx.putImageData(history[newIndex].imageData, 0, 0);
}, [history, historyIndex]);
// Clear mask
const handleClear = useCallback(() => {
const canvas = canvasRef.current;
if (!canvas)
return;
const ctx = canvas.getContext('2d');
if (!ctx)
return;
ctx.clearRect(0, 0, canvas.width, canvas.height);
saveToHistory();
}, [saveToHistory]);
// Get canvas coordinates from mouse event
const getCanvasCoords = useCallback((e) => {
const canvas = canvasRef.current;
if (!canvas)
return { x: 0, y: 0 };
const rect = canvas.getBoundingClientRect();
const x = ((e.clientX - rect.left) / rect.width) * canvas.width;
const y = ((e.clientY - rect.top) / rect.height) * canvas.height;
return { x, y };
}, []);
// Draw on canvas
const draw = useCallback((x, y) => {
const canvas = canvasRef.current;
if (!canvas)
return;
const ctx = canvas.getContext('2d');
if (!ctx)
return;
ctx.beginPath();
ctx.arc(x, y, brushSize / 2 / canvasScale, 0, Math.PI * 2);
if (mode === 'brush') {
// Draw white mask (areas to inpaint)
ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = `rgba(255, 255, 255, ${brushOpacity})`;
}
else {
// Erase
ctx.globalCompositeOperation = 'destination-out';
ctx.fillStyle = 'rgba(0, 0, 0, 1)';
}
ctx.fill();
}, [mode, brushSize, brushOpacity, canvasScale]);
// Mouse event handlers
const handleMouseDown = useCallback((e) => {
setIsDrawing(true);
const { x, y } = getCanvasCoords(e);
draw(x, y);
}, [getCanvasCoords, draw]);
const handleMouseMove = useCallback((e) => {
if (!isDrawing)
return;
const { x, y } = getCanvasCoords(e);
draw(x, y);
}, [isDrawing, getCanvasCoords, draw]);
const handleMouseUp = useCallback(() => {
if (isDrawing) {
setIsDrawing(false);
saveToHistory();
}
}, [isDrawing, saveToHistory]);
const handleMouseLeave = useCallback(() => {
if (isDrawing) {
setIsDrawing(false);
saveToHistory();
}
}, [isDrawing, saveToHistory]);
// Save mask and call callback
const handleSave = useCallback(() => {
const canvas = canvasRef.current;
if (!canvas)
return;
// Export as PNG data URL
const maskDataUrl = canvas.toDataURL('image/png');
onSaveMask(maskDataUrl);
}, [onSaveMask]);
// Keyboard shortcuts
useEffect(() => {
const handleKeyDown = (e) => {
if (e.key === 'z' && (e.ctrlKey || e.metaKey)) {
if (e.shiftKey) {
handleRedo();
}
else {
handleUndo();
}
e.preventDefault();
}
else if (e.key === 'b') {
setMode('brush');
}
else if (e.key === 'e') {
setMode('eraser');
}
else if (e.key === 'Escape') {
onCancel();
}
else if (e.key === 'Enter') {
handleSave();
}
else if (e.key === '[') {
setBrushSize((prev) => Math.max(5, prev - 5));
}
else if (e.key === ']') {
setBrushSize((prev) => Math.min(200, prev + 5));
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [handleUndo, handleRedo, onCancel, handleSave]);
return (<div className="fixed inset-0 z-50 bg-black/90 flex flex-col">
{/* Header */}
<div className="flex items-center justify-between px-6 py-4 border-b border-white/10 bg-black/50 backdrop-blur-xl">
<div className="flex items-center gap-4">
<h2 className="text-lg font-bold text-white">Draw Mask</h2>
<span className="text-xs text-white/40">
Paint the areas you want to edit (white = areas to change)
</span>
</div>
<div className="flex items-center gap-2">
<button onClick={onCancel} className="flex items-center gap-2 px-4 py-2 rounded-lg bg-white/5 hover:bg-white/10 border border-white/10 text-white/70 hover:text-white transition-colors">
<X size={16}/>
Cancel
</button>
<button onClick={handleSave} className="flex items-center gap-2 px-4 py-2 rounded-lg bg-purple-500 hover:bg-purple-400 text-white font-semibold transition-colors">
<Check size={16}/>
Apply Mask
</button>
</div>
</div>
{/* Main canvas area */}
<div ref={containerRef} className="flex-1 flex items-center justify-center p-4 overflow-hidden">
<div className="relative">
{/* Background image */}
<img src={resolveFileUrl(imageUrl)} alt="Source" className="max-w-full max-h-[70vh] object-contain rounded-lg shadow-2xl" style={{
width: imageDimensions.width * canvasScale || 'auto',
height: imageDimensions.height * canvasScale || 'auto',
}}/>
{/* Canvas overlay */}
<canvas ref={canvasRef} onMouseDown={handleMouseDown} onMouseMove={handleMouseMove} onMouseUp={handleMouseUp} onMouseLeave={handleMouseLeave} className="absolute inset-0 cursor-crosshair" style={{
width: imageDimensions.width * canvasScale || '100%',
height: imageDimensions.height * canvasScale || '100%',
opacity: showMask ? 0.6 : 0,
pointerEvents: showMask ? 'auto' : 'none',
mixBlendMode: 'screen',
}}/>
{/* Brush cursor preview */}
{showMask && (<div className="pointer-events-none absolute rounded-full border-2 border-white/50" style={{
width: brushSize,
height: brushSize,
transform: 'translate(-50%, -50%)',
left: '50%',
top: '50%',
display: 'none',
}}/>)}
</div>
</div>
{/* Toolbar */}
<div className="flex items-center justify-center gap-6 px-6 py-4 border-t border-white/10 bg-black/50 backdrop-blur-xl">
{/* Mode buttons */}
<div className="flex items-center gap-2 p-1 rounded-xl bg-white/5 border border-white/10">
<button onClick={() => setMode('brush')} className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-colors ${mode === 'brush'
? 'bg-purple-500 text-white'
: 'text-white/60 hover:text-white hover:bg-white/10'}`} title="Brush (B)">
<Brush size={18}/>
<span className="text-sm font-medium">Brush</span>
</button>
<button onClick={() => setMode('eraser')} className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-colors ${mode === 'eraser'
? 'bg-purple-500 text-white'
: 'text-white/60 hover:text-white hover:bg-white/10'}`} title="Eraser (E)">
<Eraser size={18}/>
<span className="text-sm font-medium">Eraser</span>
</button>
</div>
{/* Brush size */}
<div className="flex items-center gap-3">
<span className="text-xs text-white/40 uppercase tracking-wider font-semibold">
Size
</span>
<input type="range" min={5} max={200} value={brushSize} onChange={(e) => setBrushSize(Number(e.target.value))} className="w-32 h-1.5 bg-white/10 rounded-full appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3 [&::-webkit-slider-thumb]:bg-purple-400 [&::-webkit-slider-thumb]:rounded-full"/>
<span className="text-sm text-white/60 w-8">{brushSize}</span>
</div>
{/* Brush opacity */}
<div className="flex items-center gap-3">
<span className="text-xs text-white/40 uppercase tracking-wider font-semibold">
Opacity
</span>
<input type="range" min={0.1} max={1} step={0.1} value={brushOpacity} onChange={(e) => setBrushOpacity(Number(e.target.value))} className="w-24 h-1.5 bg-white/10 rounded-full appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3 [&::-webkit-slider-thumb]:bg-purple-400 [&::-webkit-slider-thumb]:rounded-full"/>
<span className="text-sm text-white/60 w-8">
{Math.round(brushOpacity * 100)}%
</span>
</div>
{/* Divider */}
<div className="w-px h-8 bg-white/10"/>
{/* History buttons */}
<div className="flex items-center gap-1">
<button onClick={handleUndo} disabled={historyIndex <= 0} className="p-2 rounded-lg text-white/60 hover:text-white hover:bg-white/10 disabled:opacity-30 disabled:cursor-not-allowed transition-colors" title="Undo (Ctrl+Z)">
<Undo2 size={18}/>
</button>
<button onClick={handleRedo} disabled={historyIndex >= history.length - 1} className="p-2 rounded-lg text-white/60 hover:text-white hover:bg-white/10 disabled:opacity-30 disabled:cursor-not-allowed transition-colors" title="Redo (Ctrl+Shift+Z)">
<Redo2 size={18}/>
</button>
</div>
{/* Clear button */}
<button onClick={handleClear} className="flex items-center gap-2 px-3 py-2 rounded-lg text-white/60 hover:text-red-400 hover:bg-red-500/10 transition-colors" title="Clear mask">
<Trash2 size={18}/>
<span className="text-sm font-medium">Clear</span>
</button>
{/* Toggle visibility */}
<button onClick={() => setShowMask(!showMask)} className="flex items-center gap-2 px-3 py-2 rounded-lg text-white/60 hover:text-white hover:bg-white/10 transition-colors" title="Toggle mask visibility">
{showMask ? <Eye size={18}/> : <EyeOff size={18}/>}
<span className="text-sm font-medium">{showMask ? 'Hide' : 'Show'}</span>
</button>
</div>
{/* Keyboard shortcuts help */}
<div className="absolute bottom-20 left-4 text-[10px] text-white/30 space-y-1">
<div>
<kbd className="px-1 py-0.5 bg-white/10 rounded">B</kbd> Brush
</div>
<div>
<kbd className="px-1 py-0.5 bg-white/10 rounded">E</kbd> Eraser
</div>
<div>
<kbd className="px-1 py-0.5 bg-white/10 rounded">[</kbd>{' '}
<kbd className="px-1 py-0.5 bg-white/10 rounded">]</kbd> Brush size
</div>
<div>
<kbd className="px-1 py-0.5 bg-white/10 rounded">Ctrl+Z</kbd> Undo
</div>
<div>
<kbd className="px-1 py-0.5 bg-white/10 rounded">Enter</kbd> Apply
</div>
<div>
<kbd className="px-1 py-0.5 bg-white/10 rounded">Esc</kbd> Cancel
</div>
</div>
</div>);
}
|