2008-09-26 13 views
18

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.¿Es posible manipular un documento SVG incrustado en un documento HTML con JavaScript?

Ejemplo:

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

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

Respuesta

10

Solución:

en SVG:

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

en html (usando prototipo añadir detectores de eventos):

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

Es necesario 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.

3

Hace unos años, me pidieron que creara un juego de 2 jugadores basado en Ajax 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 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 fue pura SVG + JavaScript, pero esta es la esencia de la misma.

0

Para el apoyo en IE6, echar un vistazo a SVGWeb.

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

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

5

Las cosas son más simples de lo que esperaba. 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> 
    
  • elemento Una 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 de 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> 
    
Cuestiones relacionadas