views:

327

answers:

2

Is there an easy way to render SVG inside a page using javascript? What I want to do is set up a big textarea where a user can type SVG and click a button that renders it on the page.

+5  A: 

You can use DOM to create an SVG element in your HTML.

strager
A: 

A code sample (typed, not verified):

<textarea id="input"></textarea>
<button onclick="fPreview()">preview</button>
<div id="output"></div>

<script type="text/javascript">
function fPreview() {
    var oInput = document.getElementById("input");
    var oOutput = document.getElementById("output");
    // clean preview area
    if (oOutput.firstChild)
        oOutput.removeChild(oOutput.firstChild);
    // parse text into DOM and show it in preview
    var oSVGInput = new DOMParser().parseFromString(oInput.value, "text/xml");
    if (oSVGInput.documentElement)
        oOutput.appendChild(document.importNode(oSVGInput.documentElement));
    else
        oOutput.appendChild("Unknown error");
}
</script>
Sergey Ilinsky