1

Take a look at this example:

  var c=document.getElementById("myCanvas");
   var ctx=c.getContext("2d");

    // First rectangle created    
    ctx.fillRect(20,20,150,100);

    // Second rectangle created    
    ctx.fillRect(20,150,150,100);

    // Third rectangle created    
    ctx.fillRect(20,300,150,100);

I created three rectangles here. After creating third rectangle I want to rotate first rectangle. How do i get reference of first rectangle now?

Kaushal P
  • 45
  • 1
  • 5

4 Answers4

5

A canvas is just a dumb grid of pixels. It doesn't understand what shapes have been drawn on it. Your code (or a library that your code uses) must keep track of the shapes that you've drawn.

Instead, it sounds like you want a library to create a scene graph, like EaselJS, Paper.js, or KineticJS. These libraries will maintain a data structure that tracks what shapes have been drawn on the canvas, and they will then redraw them when you want to manipulate those shapes.

apsillers
  • 112,806
  • 17
  • 235
  • 239
4

You don't "get the reference" of a rectangle or something with canvas. All you have is a canvas with a context. On which you can draw. Period.

If you want to move the first rectangle, then clear it (using clearRect) and redraw the new one.

Florian Margaine
  • 58,730
  • 15
  • 91
  • 116
2

Canvas itself is just pixels. It knows how to draw rectangles, but doesn't keep them layered.

To quote Simon Sarris:

HTML5 Canvas is simply a drawing surface for a bit map. You set up a draw (Say with a color and line thickness) , draw that thing, and then the Canvas has no knowledge of that thing: It doesn't know where it is or what it is, it's just pixels. If you want to draw rectangles and have them move around or be selectable then you have to code all of that from scratch, including the code to remember that you drew them.

The only exception is the isPointInPath method, but it has limitations.

However, there are some libraries that provide object-oriented interface for Canvas. Like Fabric.js or KineticJS. They remember what you draw as objects (rectangles, circles and so on) and can layer them one over another, move around and add mouse/touch events. Much like DOM.

Community
  • 1
  • 1
katspaugh
  • 17,449
  • 11
  • 66
  • 103
1

Drawing functions like fillRect() does not return anything (returns void).

Meaning it simply renders the pixels, it does not create a rectangle object and return it. You'll need to store the rectangle coordinates yourself.

techfoobar
  • 65,616
  • 14
  • 114
  • 135