Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

174
Views
check if circle is hovered HTML5 Canvas

I want to make a hover state for circle in canvas. Here's what I've got

Code:

let canvas = document.getElementById('canvas')
let ctx = canvas.getContext('2d')

let circle = { x: 100, y: 100, r: 30 } 

ctx.beginPath()
ctx.arc(circle.x, circle.y, circle.r, 0, Math.PI * 2)
ctx.strokeStyle = "#aaa"
ctx.lineWidth = 3
ctx.stroke()
ctx.closePath()


this.canvas.addEventListener('mousemove', e => {

    let rect = this.canvas.getBoundingClientRect()
    let position = {
        x: e.clientX - rect.left,
        y:  e.clientY - rect.top,
    }
    
    if(position.x > circle.x - circle.r &&
        position.x < circle.x + circle.r &&
        position.y < circle.y + circle.r &&
        position.y > circle.y - circle.r ) {
            this.canvas.style.cursor = 'pointer'
    } else {
        this.canvas.style.cursor = 'default'
    }

})
<canvas id="canvas" />

But in above code, it will hover as if the circle is a square.

enter image description here

It will apply the hover state outside the circle, in the every corner of square. I think it is because of the if conditions in this piece of code:

if(position.x > circle.x - circle.r &&
    position.x < circle.x + circle.r &&
    position.y < circle.y + circle.r &&
    position.y > circle.y - circle.r ) {
        this.canvas.style.cursor = 'pointer'
}

Does anyone have solution to make the hover state is working exactly inside circle?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!