Practice Combining Multiple Mouse Events
In this step, we'll create an interactive drawing application that combines multiple mouse events to demonstrate how different events can work together to create a rich user experience. We'll implement a simple drawing canvas where users can draw by clicking and dragging the mouse.
Create a new file mouse-drawing.html
in the ~/project
directory with the following code:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Interactive Drawing Canvas</title>
<style>
#drawingCanvas {
border: 2px solid #000;
background-color: #f0f0f0;
cursor: crosshair;
}
#colorPicker {
margin-bottom: 10px;
}
</style>
</head>
<body>
<h1>Interactive Drawing Canvas</h1>
<div>
<label for="colorPicker">Choose Color:</label>
<input type="color" id="colorPicker" value="#000000" />
<button id="clearCanvas">Clear Canvas</button>
</div>
<canvas id="drawingCanvas" width="600" height="400"></canvas>
<p id="drawingStatus">
Start drawing by clicking and dragging on the canvas
</p>
<script>
const canvas = document.getElementById("drawingCanvas");
const ctx = canvas.getContext("2d");
const colorPicker = document.getElementById("colorPicker");
const clearButton = document.getElementById("clearCanvas");
const drawingStatus = document.getElementById("drawingStatus");
let isDrawing = false;
let lastX = 0;
let lastY = 0;
// Mouse down event - start drawing
canvas.addEventListener("mousedown", startDrawing);
// Mouse move event - draw while mouse is pressed
canvas.addEventListener("mousemove", draw);
// Mouse up and mouse out events - stop drawing
canvas.addEventListener("mouseup", stopDrawing);
canvas.addEventListener("mouseout", stopDrawing);
// Clear canvas button
clearButton.addEventListener("click", clearCanvas);
function startDrawing(e) {
isDrawing = true;
[lastX, lastY] = [e.offsetX, e.offsetY];
drawingStatus.textContent = "Drawing in progress...";
}
function draw(e) {
if (!isDrawing) return;
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(e.offsetX, e.offsetY);
ctx.strokeStyle = colorPicker.value;
ctx.lineWidth = 2;
ctx.lineCap = "round";
ctx.stroke();
[lastX, lastY] = [e.offsetX, e.offsetY];
}
function stopDrawing() {
isDrawing = false;
drawingStatus.textContent = "Drawing stopped. Start again!";
}
function clearCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawingStatus.textContent = "Canvas cleared. Start drawing!";
}
</script>
</body>
</html>
Key features of this interactive drawing application:
- Combines multiple mouse events:
mousedown
: Start drawing
mousemove
: Continue drawing while mouse is pressed
mouseup
and mouseout
: Stop drawing
- Color picker allows changing drawing color
- Clear canvas button resets the drawing
- Status messages provide user feedback
Example interactions:
- Click and drag on the canvas to draw
- Change color using the color picker
- Click "Clear Canvas" to reset the drawing area