Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 canvas click event

Tags:

I made an array of squares

ctx.fillStyle = "rgb(0,0,0)"; for(x=0;x<=25;x++){   for(y=0;y<=25;y++){           ctx.fillRect(x, y, 20, 20);    } } 

and I want a square to change its colour when clicked. How can I do that?

I don't know much HTML5 and need some help. Thanks.

like image 422
RichadC Avatar asked Jun 18 '10 06:06

RichadC


People also ask

Does canvas support event handlers?

The Canvas event handling system closely follows the W3C DOM Event Model.

How to get the coordinates of a mouse click on a canvas element?

The coordinates of the mouse whenever a click takes place can be found by detecting the click event with an event listener and finding the event's x and y position. A function is created which takes in the canvas element and event as parameters.


1 Answers

Using jQuery:

First, we determine which cell was clicked, then you could just draw over that rectangle with a different colour:

 $("#canvas").click(function(e){      var x = Math.floor((e.pageX-$("#canvas").offset().left) / 20);     var y = Math.floor((e.pageY-$("#canvas").offset().top) / 20);     ctx.fillStyle = "rgb(255,255,255)";     ctx.fillRect(x*20, y*20, 20, 20);    }); 
like image 101
Márton Borlay Avatar answered Oct 22 '22 07:10

Márton Borlay