javascript - Having problems scripting SVGs -
i'm having trouble manipulating svgs through javascript. i'd increase length of line through clicking button. i've included code in head tag:
<script type="text/javascript"> x=135; y=135; var container = document.getelementbyid("svgbox"); var mysvg = document.createelementns("http://www.w3.org/2000/svg", "svg"); function svg() { mysvg.setattribute("version", "1.2"); mysvg.setattribute("baseprofile", "tiny"); mysvg.setattribute("height","300px"); mysvg.setattribute("width","300px"); container.appendchild(mysvg); } function line() { x=x-10; y=y-10; var l1 = document.createelementns("http://www.w3.org/2000/svg", "line"); l1.setattribute("x1", "100"); l1.setattribute("y1", "100"); l1.setattribute("x2", x); l1.setattribute("y2", y); l1.setattribute("stroke", "#05adc7"); l1.setattribute("stroke-width", "2px"); mysvg.appendchild(l1); } </script>
this body text:
<body onload="svg()"> <form> <input type="button" onclick="line()" /> </form> <div id="svgbox"> </div> </body>
but when click on button, error telling me variable "container" null. know problem is?
it works if put line var container = document.getelementbyid("svgbox");
in svg function.
function svg() { var container = document.getelementbyid("svgbox"); mysvg.setattribute("version", "1.2"); mysvg.setattribute("baseprofile", "tiny"); mysvg.setattribute("height","300px"); mysvg.setattribute("width","300px"); container.appendchild(mysvg); }
the reason container null
in code because dom has not loaded yet when line var container = document.getelementbyid("svgbox");
gets executed.
you need declare container after either domcontentloaded
event or window.onload
event fired.
Comments
Post a Comment