From 274974db101329720920d1a6c1ab47c26c3c216e Mon Sep 17 00:00:00 2001 From: Kar l5 Date: Tue, 8 Jul 2025 13:47:11 +0530 Subject: [PATCH] 8 --- src/components/DrawingCanvas.js | 51 ++++++++++++++++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/src/components/DrawingCanvas.js b/src/components/DrawingCanvas.js index 7d93403..28c0027 100644 --- a/src/components/DrawingCanvas.js +++ b/src/components/DrawingCanvas.js @@ -1,7 +1,7 @@ import React, { useState, useEffect, useRef, useCallback } from 'react'; import { ChromePicker } from 'react-color'; -// Update drawShape to handle pencil strokes +// Update drawShape to handle images const drawShape = (ctx, shape) => { ctx.beginPath(); ctx.strokeStyle = shape.color; @@ -19,6 +19,8 @@ const drawShape = (ctx, shape) => { ctx.lineTo(shape.points[i].x, shape.points[i].y); } ctx.stroke(); + } else if (shape.type === 'image' && shape.image) { + ctx.drawImage(shape.image, shape.x, shape.y, shape.width, shape.height); } }; @@ -32,6 +34,7 @@ const DrawingCanvas = () => { const [currentTool, setCurrentTool] = useState('pencil'); const [color, setColor] = useState('#000000'); const [thickness, setThickness] = useState(2); + const fileInputRef = useRef(null); // Resize canvas on window resize useEffect(() => { @@ -186,6 +189,43 @@ const DrawingCanvas = () => { // eslint-disable-next-line }, [isDrawing, lastPosition, currentTool, color, thickness, shapes]); + // Insert Image Handler + const handleInsertImage = (e) => { + const file = e.target.files[0]; + if (!file) return; + const img = new window.Image(); + img.onload = () => { + // You can set default size or let user drag to size + const x = 50, y = 50, width = img.width > 300 ? 300 : img.width, height = img.height > 300 ? 300 : img.height; + setShapes(prev => [ + ...prev, + { + type: 'image', + x, + y, + width, + height, + image: img + } + ]); + // Save to history for undo + setHistory(prev => [...prev, deepCopyShapes([...shapes, { type: 'image', x, y, width, height, image: img }])]); + setUndoHistory([]); + }; + img.src = URL.createObjectURL(file); + // Reset input so same file can be uploaded again + e.target.value = ''; + }; + + // Save Canvas Handler + const handleSaveCanvas = () => { + const canvas = canvasRef.current; + const link = document.createElement('a'); + link.download = 'drawing.png'; + link.href = canvas.toDataURL('image/png'); + link.click(); + }; + return (
@@ -194,6 +234,15 @@ const DrawingCanvas = () => { + + +
setColor(c.hex)} />