Is it possible to manipulate an SVG document embedded in an HTML doc with JavaScript?

前端 未结 7 1604
情深已故
情深已故 2020-12-05 07:31

I have made a SVG image, or more like mini application, for viewing graphs of data. I want to include this in a HTML page, and call methods on the SVG image.

Example

7条回答
  •  没有蜡笔的小新
    2020-12-05 08:16

    A few years ago, I was asked to create a 2-player Ajax-based game using SVG. It may not be precisely the solution you're looking for, but it may help you listen for events in your SVG. Here's the SVG controller:

    fyi, the SVG was being dragged and dropped (it was 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);
    }
    

    My app was pure SVG + JavaScript, but this is the gist of it.

提交回复
热议问题