Creating a simple HTML speedometer can be accomplished using a combination of HTML, CSS, and JavaScript. Below is a straightforward example demonstrating how to create a speedometer using an HTML canvas.
Here's the full implementation:
HTML (index.html)
html Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Speedometer</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f0f0f0;
}
canvas {
border: 2px solid #333;
}
</style>
</head>
<body>
<canvas id="speedometer" width="400" height="200"></canvas>
<script src="speedometer.js"></script>
</body>
</html>
JavaScript (speedometer.js)
javascript Copy code
const canvas = document.getElementById('speedometer');
const ctx = canvas.getContext('2d');
const centerX = canvas.width / 2;
const centerY = canvas.height;
const radius = 100;
// Function to draw the speedometer
function drawSpeedometer(value) {
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
// Draw the background arc
ctx.beginPath();
ctx.arc(centerX, centerY, radius, Math.PI, 0); // Draw semi-circle
ctx.lineWidth = 20;
ctx.strokeStyle = '#e1e1e1';
ctx.stroke();
// Draw the fill arc according to the speed value
ctx.beginPath();
const fillEndAngle = Math.PI + (Math.PI * (value / 100)); // Scale value to radians
ctx.arc(centerX, centerY, radius, Math.PI, fillEndAngle); // Draw arc based on value
ctx.lineWidth = 20;
ctx.strokeStyle = '#0f0'; // Green color for fill
ctx.stroke();
// Draw the speed value
ctx.fillStyle = '#333';
ctx.font = '30px Arial';
ctx.fillText(value + ' km/h', centerX - 40, centerY - 30);
}
// Simulate speed value for demonstration
let speed = 0;
const interval = setInterval(() => {
if (speed <= 100) {
drawSpeedometer(speed);
speed += 1; // Increment speed for demonstration
} else {
clearInterval(interval);
}
}, 100); // Update speed every 100ms
Explanation:
HTML Structure : A <canvas> element is used as a rendering surface for the speedometer.
Styling : Basic CSS makes sure the speedometer is centered on the page, and it adds a border to the canvas.
JavaScript Logic :
The drawSpeedometer function takes a speed value (0-100) and draws a semi-circle representing the current speed.
Two arcs are drawn: one for the background and one that fills according to the speed value.
The speed value is displayed in the center.
An interval simulates increasing speed, incrementing the speed value every 100 milliseconds until it reaches 100.
Usage:
Place the HTML code in an index.html file.
Place the JavaScript code in a speedometer.js file.
Open the index.html file in a web browser to see the speedometer in action.
You can adjust the styles and speeds as needed!