Nice programing

JavaScript로 SVG의 Z 인덱스 / 레이어를 변경할 수 있습니까?

nicepro 2020. 10. 4. 13:26
반응형

JavaScript로 SVG의 Z 인덱스 / 레이어를 변경할 수 있습니까? 요소?


몇 가지 합성 모양 ( <g>) 이 있다고 가정 해 보겠습니다 . 나는 그것들을 클릭하고 드래그 할 수 있기를 원하지만, 지금 드래그하고있는 하나가 Z 순서에서 다른 하나의 맨 위에 있기를 원합니다. 그래서 다른 하나 위로 드래그하면 다른 하나가 하나는 가려 져야합니다.


SVG의 Z 인덱스는 요소가 문서에 나타나는 순서로 정의됩니다. 특정 모양을 맨 위로 가져 오려면 요소 순서를 변경해야합니다.


트리에서 요소를 이동하는 것에 대한 대안은 원하는 z 순서를 제공하도록 속성 <use>을 변경하는 요소 를 사용 xlink:href하는 것입니다.

다음은 일부 모양을 애니메이션하려는 맥락에서이 주제를 논의하는 svg- 개발자 메일 링리스트 오래된 스레드 입니다.

최신 정보:

<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>

이 예에서 <use> 요소는 마지막 요소이므로 가장 앞쪽 요소가됩니다. xlink:href속성 을 변경하여 맨 앞에있는 다른 요소를 선택할 수 있습니다 . 위의 예에서으로 원을 선택 id="c1"하여 최상위 요소로 나타납니다.

바이올린 참조 .


이것은 오래된 질문이지만 ...

FireFox (7+) 및 Chrome (14+)에서는 svg_element를 맨 위로 가져올 수 있습니다. 이것은 완전한 z 축 제어의 자유를 제공하지 않지만 아무것도없는 것보다 낫습니다.)

해당 요소를 다시 추가하십시오.

var svg = doc.createElemNS('svg');
var circle = doc.createElemNS('circle');
var line = doc.createElemNS('line');

svg.appendChild(circle); // appends it
svg.appendChild(line);   // appends it over circle
svg.appendChild(circle); // redraws it over line now

나는 그것이 오류 같은 것을 던질 것이라고 생각했습니다.

appendChild == 자체 교체 == 다시 그리기


언급되지 않은 또 다른 해결책은 각 svg 항목 / 항목 집합을 div에 넣는 것입니다. div의 Z- 색인을 쉽게 변경할 수 있습니다.

Fiddle : 컨테이너 용 Z- 인덱스로 SVG 요소 순환

... 버튼을 눌러 해당 요소를 앞으로 밀어냅니다. (전체 세트를 다시 칠하고 1 개의 요소를 앞으로 밀지 만 허용 된 솔루션에서와 같이 원래 순서를 유지)

상대적인 z 인덱스가 있으면 매우 좋을 것입니다.

stackOverflow가 jsfiddle의 링크 인 경우 코드를 넣어달라고 원하십니까? ... ook

var orderArray=[0,1,2];
var divArray = document.querySelectorAll('.shape');
var buttonArray = document.querySelectorAll('.button');

for(var i=0;i<buttonArray.length;i++){
    buttonArray[i].onclick=function(){
        var localI = i;
        return function(){clickHandler(orderArray.indexOf(localI));};
    }();
}


function clickHandler(divIndex) {
     orderArray.push(orderArray.splice(divIndex, 1)[0]);
    orderDivs();
}

function orderDivs(){
    for(var i=0;i<orderArray.length;i++){
       divArray[orderArray[i]].style.zIndex=i;        
    }
}
svg {
    width: 100%;
    height: 100%;
    stroke: black;
    stroke-width:2px;
    pointer-events: all;
}
div{
    position:absolute;
}
div.button{
    top:55%;
    height:5%;
    width:15%;
    border-style: outset;
    cursor:pointer;
    text-align: center;
    background:rgb(175, 175, 234);
    
}
div.button:hover{
    border-style: inset;
    background:yellow;
    
}
div.button.first{
    left:0%;
}
div.button.second{
    left:20%;
}
div.button.third{
    left:40%;
}
<div class="shape">
    <svg>
    <circle cx="50" cy="50" r="40" fill="lime" />
    </svg>
</div>
<div class="shape">
    <svg>
        <rect x="4" y="20" width="200" height="50" fill="cyan" />
    </svg>
</div>
<div class="shape">
    <svg>
        <circle cx="70" cy="70" r="50" fill="fuchsia" />
    </svg>
</div>

<div class='button first'>lime</div>
<div class='button second'>cyan</div>
<div class='button third'>fuchsia</div>


svg.js 라이브러리 를 사용하는 경우 ".front ()"명령을 사용하여 모든 요소를 ​​맨 위로 이동할 수 있습니다.


예, 순서는 다른 개체 앞에 어떤 개체가 있는지 지정하는 것입니다. 순서를 조작하려면 DOM에 대한 항목을 이동해야합니다. SVG wiki ( https://www.w3.org/TR/SVG/render.html#RenderingOrder) 에 이에 대한 좋은 예가 있습니다.


SVG uses a "painters model" of rendering. Paint is applied in successive operations to the output device such that each operation paints over some area of the output device. When the area overlaps a previously painted area the new paint partially or completely obscures the old.- link to this


In SVG, to get a higher larger Z index you should move the element down in the DOM tree. You can do this with jQuery, selecting the SVG element, removing it and appending it again at the position you want:

$('g.element').remove().appendTo('svg');

Adam Bradley's comment to Sam's answer was exactly on point. It uses jQuery rather than CSS only, but he said this:

$('#thing-i-want-on-top').appendTo('#my-svg');

However, for what I was creating, I needed my SVG Path to be above any other path on hover, but still be below my SVG Text. So here's what I came up with:

$('#thing-i-want-on-top').insertBefore('#id-for-svg-text');

Both appendTo and insertBefore will move your element to a new location allowing you to change the depth of the SVG element at will.

참고URL : https://stackoverflow.com/questions/482115/with-javascript-can-i-change-the-z-index-layer-of-an-svg-g-element

반응형