Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG re-ordering z-index (Raphael optional)

How can I reorder Raphael or their underlying SVG elements after creation. Better yet, do something like layers exist in SVG?

Ideally I would like two or more layers in which to place elements at any time; A background and a foreground layer. If that is not an option, popping elements to the front would be ok, and pushing it to the back would be better in this particular case.

Thanks,

like image 611
Miles Avatar asked Jul 04 '11 00:07

Miles


3 Answers

Gimme the Code!

// move element "on top of" all others within the same grouping
el.parentNode.appendChild(el); 

// move element "underneath" all others within the same grouping
el.parentNode.insertBefore(el,el.parentNode.firstChild);

// move element "on top of" all others in the entire document
el.ownerSVGElement.appendChild(el); 

// move element "underneath" all others in the entire document
el.ownerSVGElement.appendChild(el,el.ownerSVGElement.firstChild); 

Within Raphael specifically, it's even easier by using toBack() and toFront():

raphElement.toBack()  // Move this element below/behind all others
raphElement.toFront() // Move this element above/in front of all others

Details

SVG uses a "painters model" when drawing objects: items that appear later in the document are drawn after (on top of) elements that appear earlier in the document. To change the layering of items, you must re-order the elements in the DOM, using appendChild or insertBefore or the like.

You can see an example of this here: http://phrogz.net/SVG/drag_under_transformation.xhtml

  1. Drag the red and blue objects so that they overlap.
  2. Click on each object and watch it pop to the top. (The yellow circles are intended to always be visible, however.)

The re-ordering of elements on this example is done by lines 93/94 of the source code:

el.addEventListener('mousedown',function(e){
  el.parentNode.appendChild(el); // move to top
  ...
},false);

When the mouse is pushed down on an element, it is moved to be the last element of all its siblings, causing it to draw last, "on top" of all others.

like image 131
Phrogz Avatar answered Oct 21 '22 20:10

Phrogz


If you're using Raphael, popping elements backwards and forwards is very straightforward:

element.toBack()
element.toFront()

Here's the relevant documentation.

like image 21
Herman Schaaf Avatar answered Oct 21 '22 20:10

Herman Schaaf


There's no z-index in SVG, objects that are later in the code appear above the first ones. So for your needs, you can move the node to the start of the tree or the end of it.

<g> (group) element is a generic container in svg, so they can be layers for you. Just move nodes between the groups to achieve what you need.

like image 4
Spadar Shut Avatar answered Oct 21 '22 18:10

Spadar Shut