How to check if a cursor is inside a circle on a canvas?

Member

by lizzie , in category: Javascript , 3 months ago

How to check if a cursor is inside a circle on a canvas?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lindsey.homenick , 3 months ago

@lizzie 

To check if a cursor is inside a circle on a canvas, you can follow these steps:

  1. Get the cursor coordinates (x, y) position on the canvas.
  2. Get the center coordinates (x_center, y_center) of the circle on the canvas.
  3. Calculate the distance between the cursor position and the center of the circle using the distance formula:
1
let distance = Math.sqrt((x - x_center)**2 + (y - y_center)**2);


  1. Check if the distance is less than or equal to the radius of the circle. If the distance is less than or equal to the radius, then the cursor is inside the circle.


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.