Generate a single index.html file that implements a simple interactive drawing tool using the HTML element.
The file should contain:
A visible element where drawing takes place.
JavaScript code that allows a user to draw lines on the canvas by clicking and dragging the mouse.
A small set of color options (at least 3 distinct colors) displayed as buttons or swatches. Clicking on a color option should change the drawing color for subsequent strokes.
A "Clear" button that erases all drawing on the canvas.
All HTML structure, necessary CSS for basic layout, and the JavaScript drawing and interaction logic must be self-contained within this single index.html file. Do not link to external resources. The goal is a simple, runnable drawing pad in one file.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Canvas Drawing Tool</title>
<style>
body {
font-family: sans-serif;
display: flex;
flex-direction: column;
align-items: center;
margin-top: 20px;
background-color: #f0f0f0;
}
#drawingCanvas {
border: 2px solid black;
background-color: white;
cursor: crosshair; /* Indicate drawable area */
touch-action: none; /* Prevent scrolling on touch devices */
}
.controls {
margin-top: 15px;
display: flex;
align-items: center;
gap: 10px; /* Spacing between controls */
}
.color-swatch {
width: 30px;
height: 30px;
border: 1px solid #555;
cursor: pointer;
display: inline-block;
transition: transform 0.1s ease-in-out;
}
.color-swatch:hover {
transform: scale(1.1);
}
.color-swatch.selected {
border: 3px solid gold; /* Highlight selected color */
transform: scale(1.1);
}
#clearButton {
padding: 8px 15px;
font-size: 1em;
cursor: pointer;
border: 1px solid #ccc;
border-radius: 4px;
background-color: #e7e7e7;
}
#clearButton:hover {
background-color: #d8d8d8;
}
label {
margin-right: 5px;
font-weight: bold;
}
</style>
</head>
<body>
<h1>Simple Drawing Pad</h1>
<canvas id="drawingCanvas" width="600" height="400">
Your browser does not support the HTML canvas tag.
</canvas>
<div class="controls">
<label>Color:</label>
<div class="color-swatch selected" data-color="black" style="background-color: black;"></div>
<div class="color-swatch" data-color="red" style="background-color: red;"></div>
<div class="color-swatch" data-color="blue" style="background-color: blue;"></div>
<div class="color-swatch" data-color="green" style="background-color: green;"></div>
<div class="color-swatch" data-color="yellow" style="background-color: yellow;"></div>
<div class="color-swatch" data-color="white" style="background-color: white;"></div> <!-- Eraser -->
<button id="clearButton">Clear Canvas</button>
</div>
<script>
window.addEventListener('DOMContentLoaded', () => {
const canvas = document.getElementById('drawingCanvas');
const ctx = canvas.getContext('2d');
const clearButton = document.getElementById('clearButton');
const colorSwatches = document.querySelectorAll('.color-swatch');
let isDrawing = false;
let lastX = 0;
let lastY = 0;
// --- Initial Setup ---
// Set default drawing styles
ctx.strokeStyle = 'black'; // Default color
ctx.lineWidth = 5; // Default line thickness
ctx.lineJoin = 'round'; // How lines connect
ctx.lineCap = 'round'; // Shape of line ends
// --- Helper Functions ---
function getMousePos(canvasDom, event) {
const rect = canvasDom.getBoundingClientRect();
return {
x: event.clientX - rect.left,
y: event.clientY - rect.top
};
}
function getTouchPos(canvasDom, touchEvent) {
const rect = canvasDom.getBoundingClientRect();
return {
x: touchEvent.touches[0].clientX - rect.left,
y: touchEvent.touches[0].clientY - rect.top
};
}
// --- Drawing Functions ---
function startDrawing(e) {
isDrawing = true;
let pos;
if (e.touches) {
pos = getTouchPos(canvas, e);
} else {
pos = getMousePos(canvas, e);
}
[lastX, lastY] = [pos.x, pos.y];
e.preventDefault(); // Prevent default touch actions like scrolling
}
function draw(e) {
if (!isDrawing) return; // Stop if mouse button is not pressed
let pos;
if (e.touches) {
pos = getTouchPos(canvas, e);
} else {
pos = getMousePos(canvas, e);
}
ctx.beginPath();
ctx.moveTo(lastX, lastY); // Start from last point
ctx.lineTo(pos.x, pos.y); // Draw line to current point
ctx.stroke(); // Render the line
[lastX, lastY] = [pos.x, pos.y]; // Update last position
e.preventDefault(); // Prevent default touch actions
}
function stopDrawing() {
isDrawing = false;
}
// --- Event Listeners ---
// Mouse events
canvas.addEventListener('mousedown', startDrawing);
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', stopDrawing);
canvas.addEventListener('mouseout', stopDrawing); // Stop drawing if mouse leaves canvas
// Touch events
canvas.addEventListener('touchstart', startDrawing);
canvas.addEventListener('touchmove', draw);
canvas.addEventListener('touchend', stopDrawing);
canvas.addEventListener('touchcancel', stopDrawing);
// Clear button
clearButton.addEventListener('click', () => {
// Clear the entire canvas rectangle
ctx.clearRect(0, 0, canvas.width, canvas.height);
});
// Color selection
colorSwatches.forEach(swatch => {
swatch.addEventListener('click', () => {
// Update the drawing color
ctx.strokeStyle = swatch.dataset.color;
// Update selected visual state
colorSwatches.forEach(s => s.classList.remove('selected')); // Remove from all
swatch.classList.add('selected'); // Add to clicked one
});
});
});
</script>
</body>
</html>
How this file works:
HTML Structure:
Sets up a basic HTML page with a title.
Includes a <canvas> element with the ID drawingCanvas and specific width and height attributes. This is where the drawing happens.
Contains a div with the class controls to hold the color swatches and the clear button.
Color options are represented by div elements with the class color-swatch. Each has a data-color attribute storing the CSS color name and an inline style to set its background color for visual representation. One is marked selected by default.
A standard <button> with the ID clearButton is provided.
CSS Styling (<style> block):
Provides basic centering and layout for the page elements using flexbox on the body.
Styles the canvas with a border and a crosshair cursor. touch-action: none; is added to help prevent page scrolling when drawing on touch devices.
Styles the controls container for spacing.
Styles the .color-swatch elements to look like small squares, adds a hover effect, and defines a .selected class with a distinct border to highlight the active color.
Styles the #clearButton for a standard button appearance.
JavaScript Logic (<script> block):
DOMContentLoaded Listener: Ensures the script runs only after the HTML is fully loaded and parsed.
Element References: Gets references to the canvas, its 2D rendering context (ctx), the clear button, and all color swatches.
State Variables:isDrawing (boolean flag), lastX, lastY (coordinates of the last point).
Context Setup: Sets default strokeStyle (color), lineWidth, lineJoin, and lineCap for the drawing context.
Coordinate Helper: The getMousePos and getTouchPos functions calculate the mouse/touch coordinates relative to the canvas element, accounting for potential page scrolling or element positioning.
This single file provides a functional, albeit simple, drawing application directly in the browser.
startDrawing(e): Sets isDrawing to true and records the starting coordinates (lastX, lastY). Calls e.preventDefault() for touch events.
draw(e): If isDrawing is true, it gets the current coordinates, draws a line from (lastX, lastY) to the current position using ctx.beginPath(), ctx.moveTo(), ctx.lineTo(), and ctx.stroke(), then updates lastX and lastY. Calls e.preventDefault() for touch events.
stopDrawing(): Sets isDrawing to false.
Event Listeners:
Attaches mousedown/touchstart, mousemove/touchmove, mouseup/touchend, mouseout/touchcancel event listeners to the canvas to trigger the drawing functions. mouseout and touchcancel ensure drawing stops if the pointer leaves the canvas area while pressed.
Attaches a click listener to the clearButton that calls ctx.clearRect() to erase the canvas content.
Attaches click listeners to each color-swatch. When clicked, it updates ctx.strokeStyle with the color from the data-color attribute and visually updates which swatch has the .selected class.