JavaScript가있는 HTML 문서에 포함 된 SVG 문서를 조작 할 수 있습니까?

StackOverflow https://stackoverflow.com/questions/138309

  •  02-07-2019
  •  | 
  •  

문제

데이터 그래프를보기 위해 SVG 이미지 또는 미니 애플리케이션을 만들었습니다. 이것을 HTML 페이지에 포함시키고 SVG 이미지에서 메소드를 호출하고 싶습니다.

예시:

<object id="img" data="image.svg" width="500" height="300"/>
<script>document.getElementById("img").addData([1,23,4]);</script>

SVG 문서에서 메소드를 호출 할 수 있습니까? 그렇다면 SVG 파일에 노출되는 방법을 어떻게 선언하고 HTML 문서에서 어떻게 호출합니까?

도움이 되었습니까?

해결책

해결책:

SVG에서 :

<script>document.method = function() {}</script>

HTML에서 (이벤트 리스너를 추가하기 위해 프로토 타입 사용) :

<script>$("img").observe("load", function() {$("img").contentDocument.method()});

이미지에서로드 이벤트를 들어야합니다. 이미지가로드되면 element.contentDocument SVG 문서의 문서 변수에 액세스하려면 이에 추가 된 모든 방법을 사용할 수 있습니다.

다른 팁

상황은 실제로 예상보다 간단합니다. 개념을 이해하기 위해 복잡한 튜토리얼을 읽을 필요는 없습니다. jQuery를 사용할 필요도 없습니다. 기본 레이아웃은 다음과 같습니다.

  • HTML 문서의 JavaScript 기능.

    <script type="text/javascript">
    function change(){
        var s=document.getElementById("cube");
        s.setAttribute("stroke","0000FF");
    }
    </script>
    
  • 우리가 조작하려는 SVG 요소.

    <svg width=100 height=100 style='float: left;'>
      <rect x="10" y="10" width="60" height="60" id="cube" onclick="change()" stroke=#F53F0C stroke-width=10 fill=#F5C60C />
    </svg>
    
  • 변경을 유발하는 인라인 버튼. 내 예에서는 큐브 자체를 클릭하여 이벤트를 트리거 할 수 있습니다.

    <button onclick="change()">Click</button>
    

몇 년 전, 나는 SVG를 사용하여 2 플레이어 Ajax 기반 게임을 만들 것을 요청 받았다. 정확히 원하는 솔루션이 아닐 수도 있지만 SVG에서 이벤트를 듣는 데 도움이 될 수 있습니다. SVG 컨트롤러는 다음과 같습니다.

참고로, SVG가 끌고 떨어졌다 (Stratego였습니다)

/****************** Track and handle SVG object movement *************/
var svgDoc;
var svgRoot;
var mover='';       //keeps track of what I'm dragging

///start function////
//do this onload
function start(evt){
    //set up the svg document elements
    svgDoc=evt.target.ownerDocument;
    svgRoot=svgDoc.documentElement;
    //add the mousemove event to the whole thing
    svgRoot.addEventListener('mousemove',go,false);
    //do this when the mouse is released
    svgRoot.addEventListener('mouseup',releaseMouse,false); 
}

// set the id of the target to drag
function setMove(id){ mover=id; }

// clear the id of the dragging object
function releaseMouse(){ 
    if(allowMoves == true){ sendMove(mover); }
    mover=''; 
}

// this is launched every mousemove on the doc
// if we are dragging something, move it
function go(evt){
    if(mover != '' && allowMoves != false) {
        //init it
        var me=document.getElementById(mover);

        //actually change the location
        moveX = evt.clientX-135; //css positioning minus 1/2 the width of the piece
        moveY = evt.clientY-65;
        me.setAttributeNS(null, 'x', evt.clientX-135);
        me.setAttributeNS(null, 'y', evt.clientY-65);
    }
}

function moveThis(pieceID, x, y) {
    $(pieceID).setAttributeNS(null, 'x', x);
    $(pieceID).setAttributeNS(null, 'y', y);
}

내 앱은 순수한 svg + javaScript 였지만 이것이 요점입니다.

David Dailey 박사는 가장 멋진 SVG / JS 정보로 언급 할 것입니다.http://srufaculty.sru.edu/david.dailey/svg/

Javascripts의 SVG를 탐구했습니다. 블로그보기 : Javascripts로 SVG 그래픽 스케일링

또한 참조하십시오 JQuery SVG 플러그인

IE6에서 지원하려면 살펴보십시오 svgweb.

라이브러리와 함께 제공된 샘플 코드에서 JavaScript로 SVG를 조작하는 방법에 대한 예가 있습니다.

메일 링리스트의 아카이브에는 상당한 양의 정보가 있습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top