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.
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?