Manipulate And Animate SVG Using Vanilla JavaScript – svg.onchain.js

Category: Javascript | June 9, 2022
Author:onchainjs
Views Total:355 views
Official Page:Go to website
Last Update:June 9, 2022
License:MIT

Preview:

Manipulate And Animate SVG Using Vanilla JavaScript – svg.onchain.js

Description:

SVG drawings are becoming more and more popular for representing vector graphics on the web. Be it a company logo, an icon, or emoji — SVG’s vector nature makes it perfect for scaling and resizing graphics without being pixelated.

In this post, you’ll find a super tiny JavaScript library for animating and manipulating SVG using plain JavaScript. Yup, it’s tiny (only 362 bytes minified) and supports all modern browsers on desktops and mobile devices.

How to use it:

1. Download and import the svg.onchain.js.

import {SVG} from './svg.onchain.js';

2. Create a root SVG document.

  • w – Element width.
  • h – Element height.
  • e – The parent (HTML) element.
  • o – Attribute key/value pairs
// doc(w, h, e, o)
let svgRoot = SVG.doc(300, 300, document.body)

3. Create an SVG element.

  • n – The element’s node name.
  • p – The parent (SVG) element.
  • o – Attribute key/value pairs.
// el(n, p, o)
let rect = SVG.el('rect', svgRoot, {
    width: 300, 
    height: 300
})

4. Assign attributes to the given SVG element.

  • e – The target element.
  • o – Attribute key/value pairs.
  • i – Iterator index (for internal use only).
// at(e, o, i)
SVG.at(rect, {
  fill: '#ff00aa'
})

5. Animate the SVG element.

SVG.el('animate', rect, {
  attributeName: 'rx',
  values: '0;50;0',
  dur: '5s',
  repeatCount: 'indefinite'
})

You Might Be Interested In:


Leave a Reply