@lizzie
To check if a cursor is inside a circle on a canvas, you can follow these steps:
1
|
let distance = Math.sqrt((x - x_center)**2 + (y - y_center)**2); |
Here is an example code snippet in JavaScript to demonstrate this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Get cursor position let x_cursor = e.offsetX; let y_cursor = e.offsetY; // Get center of circle let x_center = canvas.width / 2; let y_center = canvas.height / 2; // Calculate distance between cursor and center let distance = Math.sqrt((x_cursor - x_center)**2 + (y_cursor - y_center)**2); // Check if cursor is inside the circle if (distance <= radius) { console.log("Cursor is inside the circle"); } else { console.log("Cursor is outside the circle"); } |
In this code snippet, e.offsetX
and e.offsetY
represent the cursor position on the canvas, and canvas.width
and canvas.height
represent the dimensions of the canvas. radius
is the radius of the circle. This code can be added to an event listener for mouse movements to continuously check if the cursor is inside the circle.