get click event of each rectangle inside canvas?

后端 未结 5 1129
说谎
说谎 2020-12-01 08:31

I dont know how to register click event on each rectangle.

here is the sample:

http://jsfiddle.net/9WWqG/1/

5条回答
  •  粉色の甜心
    2020-12-01 09:11

    This is an old question but what was once hard to do when it was posted is now much easier.

    There are many libraries that keep track of the position of your objects that were drawn on canvas and handle all of the complexities of handling mouse interactions. See EaselJS, KineticJS, Paper.js or Fabric.js and this comparison of canvas libraries for more.

    You can also take a different approach and use Raphaël and gRaphaël to have a solution that uses SVG and VML instead of canvas and works even on IE6.

    Your example changed to use Raphaël would look like this:

    var r = Raphael(0, 0, 300, 150);
    
    r.rect(0, 0, 50, 50)
        .attr({fill: "#000"})
        .click(function () {
            alert('first rectangle clicked');
         });
    
    r.rect(75, 0, 50, 50)
        .attr({fill: "#000"})
        .click(function () {
            alert('second rectangle clicked');
         });
    

    See DEMO.

    Update 2015

    You may also be able to use ART, a retained mode vector drawing API for HTML5 canvas - see this answer for more info.

提交回复
热议问题