Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With JavaScript, can I change the Z index/layer of an SVG <g> element?

Tags:

javascript

svg

Let's say I have a couple composite shapes (<g>). I want to be able to click and drag them, but I want the one I happen to be dragging at the moment to be on TOP of the other one in the Z order, so that if I drag it over the OTHER one, the other one should be eclipsed.

like image 206
Corey Trager Avatar asked Jan 27 '09 02:01

Corey Trager


People also ask

Does z-index work with SVGs?

You can't use z-index with SVGs. In SVGs, z-index is defined by the order the element appears in the document.

How to increase z-index for SVG?

As discussed, according to the painter's model, for the element to have the highest z-index, it should be placed as the latest object to be drawn. So to increase the z-index of the “grey” circle, we will just change the position of the “grey” circle element to the last.

What is Z-index in Javascript?

Definition and Usage The zIndex property sets or returns the stack order of a positioned element. An element with greater stack order (1) is always in front of another element with lower stack order (0).

How do I convert SVG to front?

Moving an SVG selection to the front/back. Rolling over boxes will bring them to front, and clicking them, send them to the back.


2 Answers

Z index in SVG is defined by the order the elements appear in the document. You will have to change the element order if you want to bring a specific shape to the top.

like image 83
Sam Avatar answered Sep 17 '22 08:09

Sam


An alternative to moving elements in the tree is to use <use> elements where you change the xlink:href attribute so that it gives you the z ordering you want.

Here's an old thread on svg-developers mailinglist discussing this topic in context of wanting to animate some shapes.

Update:

<svg xmlns="http://www.w3.org/2000/svg"       xmlns:xlink="http://www.w3.org/1999/xlink"      style="width:100%; height: 100%">     <circle id="c1" cx="50" cy="50" r="40" fill="lime" />     <rect id="r1" x="4" y="20" width="200" height="50" fill="cyan" />     <circle id="c2" cx="70" cy="70" r="50" fill="fuchsia" />     <use id="use" xlink:href="#c1" /> </svg> 

In this example the <use> element is the last one, which makes it the frontmost element. We can choose any of the other elements to act as frontmost simply by changing the xlink:href attribute. In the above example we picked the circle with id="c1", which makes it appear as the topmost element.

See fiddle.

like image 35
Erik Dahlström Avatar answered Sep 20 '22 08:09

Erik Dahlström