Reputation: 40
I am creating a circle on my canvas. Is it possible to make my circle clickable?
function createCircle(context, x, y, radius, color) {
context.beginPath();
context.fillStyle = color;
context.arc(x, y, radius, 0, Math.PI * 2, true);
context.closePath();
context.fill();
}
Upvotes: 0
Views: 597
Reputation: 513
you can add mousedown event to your canvas or simply can add event listener as
canvas.addEventListener('mousedown', function(evt)
{
var mousePos = getMousePos(canvas, evt);
var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
//Here ur getting mouse position x and y coordinates.
},
false);
Upvotes: 0
Reputation: 16210
Sure you can. If you want to change the cursor to the hand (the way it does on links), you can do that too. Simply add an onmousemove event to your canvas, and if the mouse's distance from the center (you may have to use Pythagoras) is less than the radius, change the canvas's CSS property of cursor to pointer. Else, of course, return the CSS property to default. Similarly, add an onclick event, and detect when it is being clicked, and do your stuff when it's true. You therefore have a clickable circle in your canvas.
Upvotes: 0
Reputation: 10170
I'm not an expert but i think you should capture the click
event on the canvas
and then write a function
which check if the clicked point is inside the circle radius. (ie the difference between the clicked point and the circle origin is less than or equal to the radius).
Upvotes: 2