{
const canvas = html`<canvas width="400" height="400"></canvas>`;
const context = canvas.getContext("2d");
const pendulum = {
length: 150,
radius: 10,
angle1: Math.PI / 4,
angle2: Math.PI / 2,
angle3: (3 * Math.PI) / 4,
x: 200,
y: 200
};
function drawPendulum() {
context.clearRect(0, 0, canvas.width, canvas.height);
const { length, radius, angle1, angle2, angle3, x, y } = pendulum;
const x1 = x + length * Math.sin(angle1);
const y1 = y + length * Math.cos(angle1);
const x2 = x + length * Math.sin(angle2);
const y2 = y + length * Math.cos(angle2);
const x3 = x + length * Math.sin(angle3);
const y3 = y + length * Math.cos(angle3);
context.beginPath();
context.arc(x1, y1, radius, 0, 2 * Math.PI);
context.arc(x2, y2, radius, 0, 2 * Math.PI);
context.arc(x3, y3, radius, 0, 2 * Math.PI);
context.fill();
}
function updatePendulum(vertex, newX, newY) {
const { x, y } = pendulum;
const angle = Math.atan2(newY - y, newX - x);
pendulum[`angle${vertex}`] = angle;
drawPendulum();
}
canvas.addEventListener("mousedown", (event) => {
const { offsetX, offsetY } = event;
const { x, y } = pendulum;
const { radius } = pendulum;
const vertices = [
{
vertex: 1,
x: x + pendulum.length * Math.sin(pendulum.angle1),
y: y + pendulum.length * Math.cos(pendulum.angle1)
},
{
vertex: 2,
x: x + pendulum.length * Math.sin(pendulum.angle2),
y: y + pendulum.length * Math.cos(pendulum.angle2)
},
{
vertex: 3,
x: x + pendulum.length * Math.sin(pendulum.angle3),
y: y + pendulum.length * Math.cos(pendulum.angle3)
}
];
const clickedVertex = vertices.find((vertex) => {
return (
Math.sqrt((offsetX - vertex.x) ** 2 + (offsetY - vertex.y) ** 2) <=
radius
);
});
if (clickedVertex) {
const { vertex } = clickedVertex;
const mousemoveHandler = (event) => {
const { offsetX, offsetY } = event;
updatePendulum(vertex, offsetX, offsetY);
};
const mouseupHandler = () => {
canvas.removeEventListener("mousemove", mousemoveHandler);
canvas.removeEventListener("mouseup", mouseupHandler);
};
canvas.addEventListener("mousemove", mousemoveHandler);
canvas.addEventListener("mouseup", mouseupHandler);
}
});
drawPendulum();
return canvas;
}