htmlhtml5-canvashtml5-animation

How to identify shapes in Canvas?


If I define a canvas and draw few shapes onto it, then how can I pinpoint each of the shape or image so as to declare events and other properties on the each shape. Consider I have a Rectangle and a triangle. SO can I have some mechanism so as to define them as specific entity and can I deal with them individually. I know about KineticJS but I would like to implement this functionality on my own(For learning purpose). Can anyone pinpoint the way to do it. Or may be an algorithmic approach??


Solution

  • You can't use any existing functionality in the DOM for that. So you have to write it yourself. You could start by making an object model like this:

    function Shape(x, y) {
      var obj = {};
      obj.x = x;
      obj.y = y;
    
      obj.paint = function(canvasTarget) {
      }
    
      return obj;
    }
    
    function Rectangle(x, y, width, height) {
      var obj = Shape(x, y);
      obj.width = width;
      obj.height = height;
    
      obj.paint = function(canvasTarget) {
         //paint rectangle on the canvas
      }
    
      return obj;
    }
    
    function Canvas(target) {
      var obj = {};
      obj.target = target
      obj.shapes = [];
    
      obj.paint = function() {
         //loop through shapes and call paint
      }
    
      obj.addShape(shape) {
         this.shapes.push(shape);
      }        
    }
    

    After making the object model you could use it to draw the shapes like this:

    var cnv = new Canvas();
    cnv.addShape(new Rectangle(10,10,100,100));
    cnv.paint();
    

    Then you can handle the onclick event on the canvas and determine which shape is clicked on.