Can't Touch This Button

November 7, 2025

javascriptgame

A button that runs away from your cursor when you get too close. The core mechanic uses distance detection and vector math to calculate where the button should escape.

How It Works

Track the mouse position, calculate the distance to the button, and when the cursor gets within a threshold (150px), move the button in the opposite direction.

js
1.canvas.addEventListener("mousemove", (e) => {
2. // Get mouse position
3. const rect = canvas.getBoundingClientRect();
4. const mouseX = e.clientX - rect.left;
5. const mouseY = e.clientY - rect.top;
6.
7. // Get button position
8. const btnRect = button.getBoundingClientRect();
9. const btnCenterX = btnRect.left + btnRect.width / 2 - rect.left;
10. const btnCenterY = btnRect.top + btnRect.height / 2 - rect.top;
11.
12. // Calculate distance
13. const dx = mouseX - btnCenterX;
14. const dy = mouseY - btnCenterY;
15. const distance = Math.sqrt(dx * dx + dy * dy);
16.
17. // If too close, escape!
18. const threshold = 150;
19. if (distance < threshold) {
20. // Calculate escape direction (opposite to mouse)
21. const angle = Math.atan2(dy, dx);
22. const escapeX = btnCenterX - Math.cos(angle) * 100;
23. const escapeY = btnCenterY - Math.sin(angle) * 100;
24.
25. // Keep button on screen
26. const newX = Math.max(10, Math.min(90, (escapeX / rect.width) * 100));
27. const newY = Math.max(10, Math.min(90, (escapeY / rect.height) * 100));
28.
29. button.style.left = newX + '%';
30. button.style.top = newY + '%';
31. }
32.});

The Math Breakdown

1. Distance formula: Math.sqrt(dx * dx + dy * dy) calculates how far the cursor is from the button.

2. Angle calculation: Math.atan2(dy, dx) gets the angle from the button to the cursor.

3. Opposite direction: Subtract from button position using -Math.cos(angle) and -Math.sin(angle) to move away.

4. Boundary check: Math.max(10, Math.min(90, ...)) keeps the button within 10% and 90% of the screen.

Found this helpful? Follow for more tips and tutorials