Skip to content Skip to sidebar Skip to footer

Javascript And Svg In Html

I have the JavaScript file. I have the SVG file. Also I have HTML file. ... ...

Solution 1:

If you want to dynamically interact, using Javascript, with the svg file which is loaded into your HTML5 page, you must load the svg as inline. If you load as an <object> you cannot program it using your javascript. However you can load the svg file as xml via XMLHttpRequest and fill a DIV's innerHTML with the response. This inline SVG then can be dynamically changed via your Javascript. This works across all browsers. Try the files below.

Assume you have an SVG file(my.svg)

<svgxmlns="http://www.w3.org/2000/svg"width="400"height="400"><circleid="myCircle"cx="200"cy="200"fill="blue"r="150" /></svg>

and your HTML5 file is as below:

<!DOCTYPE html><htmlxmlns="http://www.w3.org/1999/xhtml"><head><metahttp-equiv="content-type"content="text/html; charset=UTF-8"></head><body><center><divid="svgInlineDiv"style='background-color:lightgreen;width:400px;height:400px;'></div><buttononClick=changeInlineCircleColor()>Change Circle Color</button><divid="svgObjectDiv"style='background-color:lightblue;width:400px;height:400px;'><objectdata="my.svg"type="image/svg+xml"id="objsvg"width="100%"height="100%"></object></div></center><scriptid=myScript>functionchangeInlineCircleColor()
{
    myCircle.setAttribute("fill","red")
}
</script><script>document.addEventListener("onload",inlineSVG(),false)
functioninlineSVG()
{
    varSVGFile="my.svg"var loadXML = newXMLHttpRequest;
    functionhandler(){
    if(loadXML.readyState == 4 && loadXML.status == 200)
        svgInlineDiv.innerHTML=loadXML.responseText
    }
    if (loadXML != null){
        loadXML.open("GET", SVGFile, true);
        loadXML.onreadystatechange = handler;
        loadXML.send();
    }
}
</script></body></html>

Post a Comment for "Javascript And Svg In Html"