tag manipulation img icon code and javascript html svg

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



svg manipulation css (7)

He hecho una imagen SVG, o más como 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 al 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?


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

fyi, el SVG estaba siendo arrastrado y caído (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 pura SVG + JavaScript, pero esta es la esencia de la misma.




Las cosas son más simples de lo que esperas. No es necesario que lea un tutorial intrincado para entender el concepto, 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 se puede activar haciendo clic en el cubo en sí.

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


Para soporte en IE6, eche un vistazo a SVGWeb .

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

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


Solución:

en svg:

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

en html (usando el prototipo para agregar oyentes de eventos):

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

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