<div style="display:flex; justify-content: center;">
<canvas width="500" height="500" id="myCanvas"></canvas>
</div><div style="display:flex; justify-content: center;">
<canvas width="500" height="500" id="myCanvas"></canvas>
</div><div style="display:flex; justify-content: center;">
<canvas width="500" height="500" id="myCanvas"></canvas>
</div><div style="display:flex; justify-content: center;">
<canvas width="500" height="500" id="myCanvas"></canvas>
</div>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
const r = 100;
const originX = canvas.width / 2;
const originY = canvas.height / 2;
const fps = 1000 / 60;
function getMousePos(canvas, e) {
const rect = canvas.getBoundingClientRect();
return {
x: e.clientX - rect.left,
y: e.clientY - rect.top
};
}
function calculate(deltaX, deltaY) {
const angle = Math.atan2(deltaY, deltaX) * 180 / Math.PI;
const rad = (Math.round(angle) / 360) * (2 * Math.PI);
const cos = originX + r * Math.cos(rad);
const sin = originY + r * Math.sin(rad);
return {
cos,
sin,
rad
}
}
function draw(cos, sin, rad) {
ctx.fillStyle = "white";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.strokeStyle = 'black';
ctx.arc(originX, originY, r, 0, 2 * Math.PI);
ctx.lineWidth = 2;
ctx.stroke();
ctx.beginPath();
ctx.moveTo(originX, 50);
ctx.lineTo(originX, canvas.height - 50);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(50, canvas.height / 2);
ctx.lineTo(canvas.height - 50, originX);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(originX, originY);
ctx.lineTo(cos, sin);
ctx.lineWidth = 3;
ctx.strokeStyle = 'red';
ctx.stroke();
ctx.closePath()
ctx.beginPath();
ctx.arc(cos, sin, 10, 0, 2 * Math.PI);
ctx.fillStyle = "black";
ctx.fill();
ctx.beginPath();
ctx.moveTo(originX, originY);
ctx.arc(originX, originY, 15, -Math.PI * 0.5, rad, true);
ctx.strokeStyle = "black";
ctx.lineWidth = 2;
ctx.stroke();
}
draw(250, 150);
window.document.addEventListener('mousemove', (e) => {
const mousePos = getMousePos(canvas, e);
const deltaX = mousePos.x - originX;
const deltaY = mousePos.y - originY;
const {
cos,
sin,
rad
} = calculate(deltaX, deltaY);
setTimeout(() => {
draw(cos, sin, rad);
}, fps);
});
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.