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.

Timeless DEV post...

How to write a kickass README

Arguably the single most important piece of documentation for any open source project is the README. A good README not only informs people what the project does and who it is for but also how they use and contribute to it.

If you write a README without sufficient explanation of what your project does or how people can use it then it pretty much defeats the purpose of being open source as other developers are less likely to engage with or contribute towards it.