我需要圆圈始终与线相交。我是数学函数的新手,并试图牢牢掌握它们。我认为这与 sin 和 cos 有关,但我可能是错的。为什么它的行为不符合预期?
代码笔: http ://codepen.io/philipbell/pen/PmwybL
let canvas = document.querySelector('#canvas');
let context = canvas.getContext('2d');
let width = canvas.width = window.innerWidth;
let height = canvas.height = window.innerHeight;
let centerY = height / 2;
let centerX = width / 2;
let circleSize = 10;
let Xradius = width / 2 - circleSize;
let Yradius = height / 2 - circleSize;
let angle = 0;
let dx = 10;
let dy = 10;
let distance = 20;
render();
function render() {
context.clearRect(0, 0, width, height);
context.save();
context.translate(centerX, centerY);
context.rotate(angle);
context.beginPath();
context.moveTo(0, 0);
context.lineTo(window.innerWidth, 0);
context.moveTo(distance, 0);
context.lineTo(distance - 10, -10);
context.moveTo(distance, 0);
context.lineTo(distance - 10, 10);
context.stroke();
context.restore();
// why isn't the line always intersecting the circle?
var xCos = centerX + Math.cos(angle) * Xradius;
var ySin = centerY + Math.sin(angle) * Yradius;
context.beginPath();
context.arc(xCos, ySin, circleSize, 0, Math.PI * 2, false);
context.fill();
requestAnimationFrame(render);
}
document.body.addEventListener('mousemove', (event) => {
dx = event.clientX - centerX;
dy = event.clientY - centerY;
distance = Math.sqrt(dx * dx + dy * dy)
angle = Math.atan2(dy, dx)
})