A dynamic triangle was successfully created even without a strong mathematical background. Hopefully, this solution proves to be helpful for your needs.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Triangle</title>
<style>
body {
margin: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
canvas {
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas width="500" height="500"></canvas>
<script>
let mousePosition = [0, 0];
let mouseClicked = false;
let dragged = null;
const getMousePosition = (canvas, event) => {
const rect = canvas.getBoundingClientRect();
const x = Math.min(Math.max(event.clientX - rect.left, 0), canvas.width);
const y = Math.min(Math.max(event.clientY - rect.top, 0), canvas.width);
return [x, y];
}
document.addEventListener('DOMContentLoaded', () => {
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
document.addEventListener('mousemove', (event) => {
mousePosition = getMousePosition(canvas, event);
});
document.addEventListener('mousedown', () => mouseClicked = true);
document.addEventListener('mouseup', () => mouseClicked = false);
const points = [
[50, 200, '#f00'],
[150, 50, '#0f0'],
[200, 150, '#00f'],
];
const radius = 10;
const draw = () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
const [mX, mY] = mousePosition;
for (const [index, [x, y, color]] of points.entries()) {
const hovered = (mX - x) ** 2 + (mY - y) ** 2 < radius ** 2;
const style = hovered ? 'fill' : 'stroke';
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2, true); // Outer circle
ctx[`${style}Style`] = color;
ctx[style]();
if(hovered && mouseClicked) {
dragged = index;
}
if(dragged === index) {
points[index] = [...mousePosition, color];
if(!mouseClicked) dragged = null;
}
}
ctx.beginPath();
ctx.moveTo(points[0][0], points[0][1]);
ctx.lineTo(points[1][0], points[1][1]);
ctx.lineTo(points[2][0], points[2][1]);
ctx.lineTo(points[0][0], points[0][1]);
ctx.strokeStyle = '#000';
ctx.stroke();
window.requestAnimationFrame(draw);
}
window.requestAnimationFrame(draw);
});
</script>
</body>
</html>