Building a Live SVG Editor in the Browser — Syntax Highlighting Without a Library
Building a Live SVG Editor in the Browser — Syntax Highlighting Without a Library A live SVG editor sounds simple: textarea on the left, preview on the right, update on change. In practice, there are several sharp edges. Rendering SVG Safely The naive approach — innerHTML = userInput — is an XSS vector. SVG can contain <script> tags and event handlers. The safer approach uses DOMParser : function…
Building a live SVG editor in the browser involves several challenges. Rendering SVG safely is a primary concern, as the naive approach using innerHTML = userInput creates an XSS vector. SVG can contain script tags and event handlers, making safer rendering necessary.
To render SVG safely, a function named renderSVG is defined. This function takes an SVG string and a container element as input. It uses DOMParser to parse the SVG string into a document object. If the parser encounters any errors, such as the presence of script tags or event handlers, it returns an object indicating the failure.
If no errors are found, the function removes any script elements and event handlers from the document. It then sets the container element's innerHTML to the parsed document's content and appends the document's root element to the container.
Converting SVG to PNG in the browser requires an intermediate step through an img element. The svgToPng function takes an SVG string, width, and height as input. It creates a Blob object from the SVG string and generates a URL for the Blob. A new Promise is returned, which resolves with a canvas converted to a PNG data URL. The Promise resolves once the img element has loaded, at which point the canvas is created with the specified width and height, and its 2D context draws the img element onto the canvas. The object URL for the Blob is revoked, and the canvas is converted to a PNG data URL.
ViewBox and zooming in SVG present their own challenges. SVG has its own coordinate system defined by the viewBox attribute. When zooming, it is essential to scale the container rather than modifying the viewBox itself, as this helps maintain consistent SVG coordinates. The setZoom function takes a container element and a scale factor as input. It sets the container's style transform property to scale the container by the specified factor and sets the transformOrigin to the top left corner.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.