Creating a basic drawing web application is an excellent way to familiarize yourself with HTML5's <canvas> element and JavaScript's event handling. Below is a step-by-step guide to building a simple drawing app where users can draw on a canvas, change brush colors, adjust brush sizes, and clear the canvas.
1. HTML Structure
Start by setting up the HTML structure, which includes a <canvas> element for drawing and a toolbar with controls for color selection, brush size adjustment, and a clear button.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
<title>Simple Drawing App</title>
<style>
body {
display: flex;
flex-direction: column;
align-items: center;
margin: 0;
padding: 20px;
}
canvas {
border: 1px solid black;
cursor: crosshair;
}
.toolbar {
margin-bottom: 10px;
}
.toolbar button, .toolbar input {
margin-right: 10px;
}
</style>
</head>
<body>
<div class="toolbar">
<input id="colorPicker" type="color" value="#000000"/>
<input id="brushSize" max="50" min="1" type="number" value="5"/>
<button id="clearCanvas">Clear</button>
</div>
<canvas height="600" id="drawingCanvas" width="800"></canvas>
<script src="app.js"></script>
</body>
</html>
2. JavaScript Functionality
Next, implement the drawing functionality using JavaScript. This involves setting up event listeners for mouse actions and handling the drawing logic.
const canvas = document.getElementById('drawingCanvas');
const ctx = canvas.getContext('2d');
const colorPicker = document.getElementById('colorPicker');
const brushSize = document.getElementById('brushSize');
const clearCanvas = document.getElementById('clearCanvas');
let isDrawing = false;
let lastX = 0;
let lastY = 0;
canvas.addEventListener('mousedown', (e) => {
isDrawing = true;
[lastX, lastY] = [e.offsetX, e.offsetY];
});
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', () => isDrawing = false);
canvas.addEventListener('mouseout', () => isDrawing = false);
function draw(e) {
if (!isDrawing) return;
ctx.strokeStyle = colorPicker.value;
ctx.lineWidth = brushSize.value;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
[lastX, lastY] = [e.offsetX, e.offsetY];
}
clearCanvas.addEventListener('click', () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
});
Explanation:
This basic drawing application provides a foundation that you can expand upon by adding features like saving the drawing as an image, adding different brush shapes, or implementing an eraser tool. For more advanced functionalities, such as real-time collaborative drawing, you can explore integrating WebSockets to synchronize drawings across multiple users[1].
By building this application, you'll gain practical experience with the HTML5 Canvas API and JavaScript event handling, which are valuable skills for creating interactive web applications.