Okay, this is a fun challenge! Creating a full-fledged CAD software like AutoCAD or SolidWorks in a single HTML file is impossible due to their immense complexity. However, we can create a very, very basic 2D drawing tool that mimics some CAD-like functionalities using HTML, CSS, and JavaScript (specifically the HTML5 Canvas API).
This will be a simplified "vector" drawing program where you can draw lines, rectangles, and circles.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mini CAD - Single File</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
align-items: center;
background-color: #f0f0f0;
}
#controls {
background-color: #333;
color: white;
padding: 10px;
margin-bottom: 10px;
width: 100%;
box-sizing: border-box;
text-align: center;
display: flex;
justify-content: center;
align-items: center;
gap: 15px; /* Spacing between control groups */
}
#controls button, #controls input, #controls select, #controls label {
padding: 8px 12px;
margin: 0 5px;
border: none;
border-radius: 4px;
cursor: pointer;
background-color: #555;
color: white;
}
#controls button:hover, #controls select:hover {
background-color: #777;
}
#controls button.active {
background-color: #007bff;
}
#controls input[type="color"] {
padding: 0; /* Remove padding for color input */
width: 40px;
height: 30px;
border: 1px solid #777;
vertical-align: middle;
}
#controls input[type="range"] {
vertical-align: middle;
}
#drawingCanvas {
border: 2px solid #333;
background-color: white;
cursor: crosshair;
touch-action: none; /* Prevent scrolling on touch devices while drawing */
}
.control-group {
display: flex;
align-items: center;
gap: 5px;
border: 1px solid #666;
padding: 5px;
border-radius: 5px;
}
</style>
</head>
<body>
<div id="controls">
<div class="control-group">
<label>Tool:</label>
<button id="lineTool" class="tool-btn active">Line</button>
<button id="rectTool" class="tool-btn">Rectangle</button>
<button id="circleTool" class="tool-btn">Circle</button>
<!-- <button id="selectTool" class="tool-btn">Select</button> -->
</div>
<div class="control-group">
<label for="strokeColor">Color:</label>
<input type="color" id="strokeColor" value="#000000">
</div>
<div class="control-group">
<label for="lineWidth">Width:</label>
<input type="range" id="lineWidth" min="1" max="20" value="2">
<span id="lineWidthValue">2px</span>
</div>
<div class="control-group">
<button id="undoBtn">Undo</button>
<button id="clearBtn">Clear All</button>
</div>
</div>
<canvas id="drawingCanvas"></canvas>
<script>
const canvas = document.getElementById('drawingCanvas');
const ctx = canvas.getContext('2d');
const controls = document.getElementById('controls');
const toolBtns = document.querySelectorAll('.tool-btn');
const strokeColorInput = document.getElementById('strokeColor');
const lineWidthInput = document.getElementById('lineWidth');
const lineWidthValueSpan = document.getElementById('lineWidthValue');
const clearBtn = document.getElementById('clearBtn');
const undoBtn = document.getElementById('undoBtn');
let currentTool = 'line'; // 'line', 'rect', 'circle'
let drawing = false;
let startX, startY;
let shapes = []; // Array to store drawn shapes
let tempShape = null; // For previewing shapes
function resizeCanvas() {
// Leave some space for controls
const controlsHeight = controls.offsetHeight + 20; // 20 for margin
canvas.width = window.innerWidth * 0.95;
canvas.height = (window.innerHeight - controlsHeight) * 0.9;
redrawAllShapes(); // Redraw after resize
}
function getMousePos(canvas, evt) {
const rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
function getTouchPos(canvas, evt) {
const rect = canvas.getBoundingClientRect();
return {
x: evt.touches[0].clientX - rect.left,
y: evt.touches[0].clientY - rect.top
};
}
function drawShape(shape) {
ctx.beginPath();
ctx.strokeStyle = shape.color;
ctx.lineWidth = shape.lineWidth;
switch (shape.type) {
case 'line':
ctx.moveTo(shape.startX, shape.startY);
ctx.lineTo(shape.endX, shape.endY);
break;
case 'rect':
ctx.rect(shape.x, shape.y, shape.width, shape.height);
break;
case 'circle':
ctx.arc(shape.centerX, shape.centerY, shape.radius, 0, 2 * Math.PI);
break;
}
ctx.stroke();
}
function redrawAllShapes() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
shapes.forEach(drawShape);
if (tempShape) { // Draw the temporary shape being previewed
drawShape(tempShape);
}
}
function startDraw(e) {
e.preventDefault(); // Prevent default actions like text selection
drawing = true;
const pos = e.type.startsWith('touch') ? getTouchPos(canvas, e) : getMousePos(canvas, e);
startX = pos.x;
startY = pos.y;
// Initialize tempShape for preview
tempShape = {
type: currentTool,
color: strokeColorInput.value,
lineWidth: parseInt(lineWidthInput.value),
startX: startX,
startY: startY,
endX: startX, // For line
endY: startY, // For line
x: startX, // For rect
y: startY, // For rect
width: 0, // For rect
height: 0, // For rect
centerX: startX, // For circle
centerY: startY, // For circle
radius: 0 // For circle
};
}
function draw(e) {
if (!drawing) return;
e.preventDefault();
const pos = e.type.startsWith('touch') ? getTouchPos(canvas, e) : getMousePos(canvas, e);
const currentX = pos.x;
const currentY = pos.y;
// Update tempShape for preview
tempShape.color = strokeColorInput.value; // Ensure current color is used for preview
tempShape.lineWidth = parseInt(lineWidthInput.value);
switch (currentTool) {
case 'line':
tempShape.endX = currentX;
tempShape.endY = currentY;
break;
case 'rect':
tempShape.x = Math.min(startX, currentX);
tempShape.y = Math.min(startY, currentY);
tempShape.width = Math.abs(currentX - startX);
tempShape.height = Math.abs(currentY - startY);
break;
case 'circle':
// Center is the start point
const dx = currentX - startX;
const dy = currentY - startY;
tempShape.radius = Math.sqrt(dx * dx + dy * dy);
break;
}
redrawAllShapes(); // Redraw everything including the temp shape
}
function stopDraw(e) {
if (!drawing) return;
drawing = false;
e.preventDefault();
const pos = e.type.startsWith('touch') ? getTouchPos(canvas, e.changedTouches[0]) : getMousePos(canvas, e); // Use changedTouches for touchend
const endX = pos.x;
const endY = pos.y;
const shape = {
type: currentTool,
color: strokeColorInput.value,
lineWidth: parseInt(lineWidthInput.value)
};
switch (currentTool) {
case 'line':
shape.startX = startX;
shape.startY = startY;
shape.endX = endX;
shape.endY = endY;
break;
case 'rect':
shape.x = Math.min(startX, endX);
shape.y = Math.min(startY, endY);
shape.width = Math.abs(endX - startX);
shape.height = Math.abs(endY - startY);
break;
case 'circle':
shape.centerX = startX;
shape.centerY = startY;
const dx = endX - startX;
const dy = endY - startY;
shape.radius = Math.sqrt(dx * dx + dy * dy);
break;
}
// Only add shape if it has some dimension (e.g., not just a click)
if ((currentTool === 'line' && (startX !== endX || startY !== endY)) ||
(currentTool === 'rect' && (shape.width > 0 || shape.height > 0)) ||
(currentTool === 'circle' && shape.radius > 0)) {
shapes.push(shape);
}
tempShape = null; // Clear temp shape
redrawAllShapes();
}
// Event Listeners
canvas.addEventListener('mousedown', startDraw);
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', stopDraw);
canvas.addEventListener('mouseout', () => { // Stop drawing if mouse leaves canvas
if (drawing) {
// Optionally, you could finalize the shape here as if mouseup occurred
// or simply set drawing = false to cancel.
// For simplicity, we'll just ensure drawing stops.
// To finalize:
// const fakeEvent = { clientX: lastKnownX, clientY: lastKnownY }; // requires tracking lastKnownX/Y
// stopDraw(fakeEvent);
drawing = false;
tempShape = null;
redrawAllShapes(); // Clear any preview
}
});
// Touch events
canvas.addEventListener('touchstart', startDraw);
canvas.addEventListener('touchmove', draw);
canvas.addEventListener('touchend', stopDraw);
canvas.addEventListener('touchcancel', () => {
drawing = false;
tempShape = null;
redrawAllShapes();
});
toolBtns.forEach(btn => {
btn.addEventListener('click', () => {
toolBtns.forEach(b => b.classList.remove('active'));
btn.classList.add('active');
currentTool = btn.id.replace('Tool', ''); // e.g., 'lineTool' -> 'line'
});
});
lineWidthInput.addEventListener('input', (e) => {
lineWidthValueSpan.textContent = `${e.target.value}px`;
});
clearBtn.addEventListener('click', () => {
if (confirm("Are you sure you want to clear everything?")) {
shapes = [];
tempShape = null;
redrawAllShapes();
}
});
undoBtn.addEventListener('click', () => {
if (shapes.length > 0) {
shapes.pop();
tempShape = null;
redrawAllShapes();
}
});
// Initial setup
window.addEventListener('resize', resizeCanvas);
resizeCanvas(); // Call once on load
lineWidthValueSpan.textContent = `${lineWidthInput.value}px`; // Set initial width display
</script>
</body>
</html>
How to use:
Save the code above as an index.html file (or any name ending with .html).
Open this HTML file in a modern web browser (Chrome, Firefox, Edge, Safari).
Features:
Drawing Tools: Line, Rectangle, Circle.
Color Picker: Choose stroke color.
Line Width: Adjust line thickness.
Canvas: A dedicated area for drawing.
Undo: Removes the last drawn shape.
Clear All: Clears the entire canvas.
Responsive Canvas: The canvas tries to resize with the browser window.
Live Preview: Shows a "ghost" of the shape as you draw.
Touch Support: Basic touch support for drawing on tablets/phones.
Limitations & Potential Improvements (for a more advanced project):
No Saving/Loading: Drawings are lost on page refresh. (Could use localStorage for very simple persistence, or server-side for real saving).
No Selection/Modification: Once a shape is drawn, you can't select it to move, resize, or delete individually (except via Undo). This is a core CAD feature and complex to implement.
No Layers: All shapes are on a single layer.
No Text Tool.
No Snapping or Grids.
No Fill Colors: Only strokes. (Easy to add ctx.fillStyle and ctx.fill()).
No Complex Shapes: Polygons, splines, etc., are not included.
Performance: For a very large number of shapes, redrawing all of them on every mouse move can become slow. Optimizations like drawing to an offscreen canvas or only redrawing affected regions would be needed.
Zoom/Pan: Essential for CAD, not implemented here.
This example demonstrates the basics of using the HTML5 Canvas for drawing. Building a true CAD system is a monumental task, but this should give you a starting point for a simple drawing application!