The canvas itself is just pixels. He knows how to draw rectangles, but does not make them layered.
To quote Simon Sarris :
HTML5 Canvas is just a drawing surface for a bitmap. You created (Tell me the color and thickness of the line), draw this thing, and then the Canvas does not know about it: it does not know where it is or what it is, it's just pixels. If you want to draw rectangles and ask them to move or be selected, then you must encode everything from scratch, including the code, to remember that you drew them.
The one exception is the isPointInPath method, but it has limitations.
However, there are some libraries that provide an object-oriented interface for Canvas. For example Fabric.js or KineticJS . They remember that you draw as objects (rectangles, circles, etc.), and you can stack them on top of each other, move around and add mouse / touch events. Very similar to the DOM.
source share