DEV Community

pabloalmunia
pabloalmunia

Posted on

Create SVG from Javascript

Creating a simple SVG requires many lines of code from JavaScript. The source code for creating and manipulating SVG elements tends to grow uncontrollably. Over time it isn't straightforward to understand and maintain the code.

This code creates a rectangle with SVG:

const div = document.querySelector('#drawing');
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('width', '100px');
svg.setAttribute('height', '100px');
div.appendChild(svg);
const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
rect.setAttribute('x', '10');
rect.setAttribute('y', '10');
rect.setAttribute('width', '90');
rect.setAttribute('height', '90');
rect.setAttribute('fill', '#F06');
svg.appendChild(rect);
Enter fullscreen mode Exit fullscreen mode

Exist libraries to keep this code most uncomplicated:

The last one, Graphery SVG, uses a very useful call chain (in the style of JQuery), which allows you to create dynamic SVG content very quickly and easily.

The previous code is reduced to:

const svg = gySVG().width('100px').height('100px');
const rect = svg.add('rect').x(10).y(10).width(90).height(90).fill('#f06');
svg.attachTo('#drawing');
Enter fullscreen mode Exit fullscreen mode

The SVG code is very similar to this Graphery SVG Javascript code:

<svg viewBox="0,0,100,100" width="100px" height="100px">
  <rect x="10" y="10" width="90" height="90" fill="#f06"></rect></svg>
Enter fullscreen mode Exit fullscreen mode

Graphery SVG is a well-documented library, and it is possible to create very attractive and dynamic SVG.

Please, share your opinion about this solution.

Top comments (1)

Collapse
 
felipex profile image
Felipe Cavalcante

Good discussion, @pabloalmunia, thanks for sharing.
This approach of Graphery SVG allow a straight one-to-one relationship (method->tag/attribute) and this contibutes to the learning curve is very smooth, ideal for small projects. In big projects I guess a lib like SNAP is most interesting because it's more semantic.