Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

175
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda