¿Es posible manipular un documento SVG incrustado en un documento HTML con JavaScript?

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

  •  02-07-2019
  •  | 
  •  

Pregunta

He creado una imagen SVG, o más como una mini aplicación, para ver gráficos de datos. Quiero incluir esto en una página HTML, y llamar a métodos en la imagen SVG.

Ejemplo:

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

¿Es posible llamar métodos en el documento SVG? Si es así, ¿cómo declaro los métodos para exponer en el archivo SVG y cómo los llamo desde el documento HTML?

¿Fue útil?

Solución

Solución:

en svg:

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

en html (usando un prototipo para agregar escuchas de eventos):

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

Necesitas escuchar el evento de carga en la imagen. Una vez que se haya cargado la imagen, puede usar element.contentDocument para acceder a la variable del documento en el documento svg. Cualquier método agregado a eso, estará disponible.

Otros consejos

Las cosas son en realidad más simples de lo que esperas. Realmente no es necesario leer el tutorial complicado para comprender el concepto, ni tampoco tiene que usar JQuery. Aquí está el diseño básico:

  • Una función de JavaScript en su documento html.

    <script type="text/javascript">
    function change(){
        var s=document.getElementById("cube");
        s.setAttribute("stroke","0000FF");
    }
    </script>
    
  • Un elemento SVG que estamos tratando de manipular.

    <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>
    
  • Un botón en línea que activaría el cambio. Tenga en cuenta que en mi ejemplo, el evento también puede activarse haciendo clic en el cubo mismo.

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

Hace unos años, me pidieron que creara un juego basado en Ajax para 2 jugadores utilizando SVG. Puede que no sea precisamente la solución que está buscando, pero puede ayudarlo a escuchar eventos en su SVG. Aquí está el controlador SVG:

fyi, el SVG estaba siendo arrastrado y soltado (era 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);
}

Mi aplicación era SVG + JavaScript puro, pero esto es lo esencial.

Me referiría al Dr. David Dailey como la información SVG / JS más impresionante que encontrarás http://srufaculty.sru.edu/david.dailey/svg/

He explorado el svg por JavaScripts. Consulte el blog: Escalado de gráficos SVG con JavaScripts

Para obtener soporte en IE6, consulte SVGWeb .

Hay ejemplos de cómo manipular SVG con JavaScript en el código de muestra suministrado con la biblioteca.

También hay una buena cantidad de información en los archivos de la lista de correo.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top