To create a simple webpage with a rotating triangle using HTML, CSS, and JavaScript, you can follow these steps:
- Create the HTML structure with a canvas element to draw the triangle.
- Use CSS to define the style of the canvas.
- Use JavaScript to create the triangle and make it rotate.
Below is the full code for the webpage:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rotating Triangle</title>
<style>
canvas {
border: 1px solid black;
display: block;
margin: 0 auto;
background-color: #f0f0f0;
}
</style>
</head>
<body>
<canvas id="triangleCanvas" width="200" height="200"></canvas>
<script>
var canvas = document.getElementById('triangleCanvas');
var ctx = canvas.getContext('2d');
var angle = 0;
function drawTriangle() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
ctx.save(); // Save the current state
ctx.translate(canvas.width / 2, canvas.height / 2); // Move to the center of the canvas
ctx.rotate(angle * Math.PI / 180); // Rotate the canvas
// Draw the triangle
ctx.beginPath();
ctx.moveTo(0, -50);
ctx.lineTo(50, 50);
ctx.lineTo(-50, 50);
ctx.closePath();
// Style the triangle
ctx.fillStyle = '#333';
ctx.fill();
ctx.stroke();
ctx.restore(); // Restore the original state
angle += 1; // Increase the angle for rotation
if (angle > 360) {
angle = 0;
}
}
// Rotate the triangle every 1 second
setInterval(drawTriangle, 1000);
</script>
</body>
</html>
What this code does:
- It defines a
canvas element in HTML with the id "triangleCanvas".
- It styles the canvas with a border and a background color using CSS.
- It uses JavaScript to get the canvas context and define a
drawTriangle function that:
- Clears the previous triangle drawing.
- Saves the current canvas state.
- Translates the context to the center of the canvas and rotates it by
angle degrees.
- Draws a triangle in the new rotated context.
- Fills the triangle with a color and outlines it.
- Restores the context to its original state.
- Increments the
angle by 1 degree to prepare for the next rotation.
- It sets an interval to call the
drawTriangle function every 1000 milliseconds (1 second), making the triangle rotate clockwise by 1 degree each second.
Copy and paste the above code into an HTML file and open it in a web browser to see the rotating triangle in action. If you want the triangle to make a complete rotation every second, you would need to adjust the increment of angle and the interval to match your requirements.