22

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.

1

2 Answers 2

31

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);


 });
Sign up to request clarification or add additional context in comments.

Comments

6

This beta build by Caleb Evans might help. Following events are included...

  • click
  • dblclick
  • mousedown
  • mouseup
  • mousemove

Link to demo on jsFiddle.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.