JSFiddle - React, Tailwind, and code Playground
by Julien Etienne
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Octagon Canvas</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="octagonCanvas" width="400" height="400"></canvas>
<script src="octagon.js"></script>
</body>
</html>
JavaScript
const canvas = document.getElementById('octagonCanvas');
const ctx = canvas.getContext('2d');
function drawOctagon(longSide, shortSide) {
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const points = [];
// Calculate the coordinates of the octagon vertices
for (let i = 0; i < 8; i++) {
let angle = (Math.PI / 2) * i; // 45 degrees in radians
let radius = (i % 2 === 0) ? longSide : shortSide;
let x = centerX + Math.cos(angle) * radius;
let y = centerY + Math.sin(angle) * radius;
points.push({ x, y });
}
// Begin drawing the octagon
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
for (let i = 1; i < points.length; i++) {
ctx.lineTo(points[i].x, points[i].y);
}
ctx.closePath();
ctx.stroke();
}
// Define long and short sides
const longSide = 80; // Length of vertical and horizontal sides
const shortSide = 50; // Length of diagonal sides
// Draw the octagon
drawOctagon(longSide, shortSide);