Day 60 Project: Drawing App
Canvas API + Mouse Events + DOM — sab combine karke ek professional Drawing App banate hain jisme drawing tools, colors, shapes, aur save functionality hogi.
Drawing Logic
Mouse events se free-hand drawing.
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight - 60; // toolbar ke liye space
let isDrawing = false;
let lastX = 0, lastY = 0;
let color = "#caff46";
let lineWidth = 5;
let tool = "brush"; // brush, eraser, line
function getPos(e) {
const rect = canvas.getBoundingClientRect();
const clientX = e.touches ? e.touches[0].clientX : e.clientX;
const clientY = e.touches ? e.touches[0].clientY : e.clientY;
return { x: clientX - rect.left, y: clientY - rect.top };
}
canvas.addEventListener("mousedown", e => {
isDrawing = true;
const pos = getPos(e);
[lastX, lastY] = [pos.x, pos.y];
});
canvas.addEventListener("mousemove", e => {
if (!isDrawing) return;
const pos = getPos(e);
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(pos.x, pos.y);
ctx.strokeStyle = tool === "eraser" ? "var(--bg)" : color;
ctx.lineWidth = tool === "eraser" ? lineWidth * 5 : lineWidth;
ctx.lineCap = "round";
ctx.lineJoin = "round";
ctx.stroke();
[lastX, lastY] = [pos.x, pos.y];
});
canvas.addEventListener("mouseup", () => isDrawing = false);
canvas.addEventListener("mouseleave", () => isDrawing = false);
// Save as image
function saveDrawing() {
const link = document.createElement("a");
link.download = "my-drawing.png";
link.href = canvas.toDataURL();
link.click();
}
// Touch support
canvas.addEventListener("touchstart", e => { e.preventDefault(); canvas.dispatchEvent(new MouseEvent("mousedown", e.touches[0])); });
canvas.addEventListener("touchmove", e => { e.preventDefault(); canvas.dispatchEvent(new MouseEvent("mousemove", e.touches[0])); });
canvas.addEventListener("touchend", () => isDrawing = false);
🎯 Practice Challenge
Drawing app mein: undo/redo functionality, fill bucket tool, aur shape tools (rectangle, circle) add karo.