Snap Docs  More SVG Dabbles

Loading SVG

Lets get an SVG shape loaded and displayed. We need a callback for when the file is loaded, then we can add it to our canvas.
Note, it gets loaded into Snap as a fragment.



function handleFileOpen(evt) {
	var inputObj = document.createElement ("input");
	inputObj.type = "file";
	inputObj.name = "document";
	document.getElementById('fileContainer2').appendChild(inputObj);
	inputObj.click();
	inputObj.addEventListener('change', handleFileSelect, false);
}


function handleFileSelect(evt) {

    var files = evt.target.files; // FileList object
    for (var i = 0, f; f = files[i]; i++) {

      var reader = new FileReader();
        reader.onload = function( evt ) {
                var contents = evt.target.result;
		s.append( Snap.parse( contents ) );
      };

      reader.onerror = function(event) {
                	console.log(' couldnt not read file. Code ' + event.target.error.code);
     		};
      reader.readAsText(f);
    };

}

var s = Snap("#svgout"); 

var button = s.rect(10,10,40,40,5,5).attr({ fill: "red", stroke: "black" });
s.text(60,30,"click Me");
button.click( handleFileOpen );

// just use a normal div below, not a foreignobject, just using this to test doing something
var fo = '<svg><foreignObject width="80" height="0"><div id="fileContainer2"></div></foreignObject></svg>';
s.group().append( Snap.parse( fo ) );



   
	
SVGout area...
The actual svg markup looks like this (when you've clicked on run)....