What is SVG?
SVG stands for scalable vector graphics and is used to define vector-based graphics for the web in XML format.
Here is a very simple example of an SVG (yellow circle with green border):
<svg width="100" height="100"> <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" /> </svg>
Why a new SVG library?
The main goal is to reduce code complexity. Even though there have been many SVG libraries over the years, there was still a need to build a new library that was smaller and faster, and closer to the SVG format. The result is gySVG. In previous SVG libraries, the minimized library size was less around 3 KB; this value is reduced to 1.5 KB with gzip. Graphery SVG is also faster, taking 20ms compared to 40ms for SVG.js.
gySVG is a simple library that provides an easy way to work with SVG without penalizing the project performance or size.
const div = document.querySelector('#drawing'); const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); svg.setAttribute('width', '100%'); svg.setAttribute('height', '100%'); 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);
Creating the same SVG with gySVG
const svg = gySVG().width('100%').height('100%'); const rect = svg.add('rect').x(10).y(10).width(90).height(90).fill('#f06'); svg.attachTo('#drawing');
The result is an entirely valid SVG that can be used without limitations as part of the HTML DOM. As you can see, it is a much simpler block.
Proxy is supported by:
- Microsoft Edge 12, and later
- Firefox 18, and later
- Chrome 49, and later
- Safari 10 desktop and mobile, and beyond
- Opera 36, and later
Proxy is not supported by Internet Explorer 11, and is cannot be integrated using polyfills or transpilers.
Getting started with gySVG
There are two methods to get started with gySVG: load from CDN or install locally with
Load from CDN
When loading from CDN, either use Import module or load the script version. The easiest way to use gySVG library is to import it as an ES module from our CDN service:
import gySVG from 'https://cdn.graphery.online/svg/0.1.4/module/index.js';
Another easy way is to load the script version from our CDN with a tag
Install locally with
You can install the Graphery SVG library locally by
npm install @graphery/svg
If you have installed locally, you’ll need to reference
node_modules/@graphery/svg and use this code for import:
import SVG from './node_modules/@graphery/svg/index.js';
Or, load script as follows:
If you use webpack or other loaders, you may be able to omit the
node_modules folder in these calls.
Understanding the SVG element
gySVG() creates an SVG element and returns an object with a gySVG wrapper over that element. It can be used to nest other elements, define its coordinate system, or establish other configuration parameters.
const svg = gySVG();
The above acts similarly to having the SVG HTML tags (
For display elements, you can use the method
.viewBox() to define the graphic’s internal canvas, while the methods
.height() can be used to define the viewport. We will discuss these in more detail in the following sections.
.viewBox() method defines the internal position and dimensions of an SVG. It makes use of four parameters:
height. These numbers specify a rectangle that is mapped within the internal boundaries associated with the SVG element. All measures of nested elements take these dimensions as a reference. Calling this method without parameters will return the current viewbox value.
const svg = gySVG().viewBox(0, 0, 100, 100);
Width and height
These methods are used to define the viewport, i.e, the image’s size in the HTML page where they will be embedded. The horizontal length is defined with
.width() and the vertical length is defined with
const svg = gySVG().width(100).height(100);
Attaching to DOM element
Finally, to include the SVG within the DOM of our HTML page, we use the
.attachTo() method, which provides a parameter as a selector to locate the element. As a result, our SVG is inserted into the page.
const svg = gySVG().viewBox(0, 0, 100, 100).width(50).height(50); svg.attachTo('#content')
Before we continue on to see how to create basic shapes like circles and rectangles using gySVG, we will first review how to add nested elements.
Add nested elements
To add elements within the SVG we will use
.add() method passing a parameter with the name of the element that we want to create. This method returns an object which we can use to set up all the characteristics of the element we have named (in this example,
const svg = gySVG().viewBox(0, 0, 100, 100).width(75).height(75); const circle = svg.add('circle').cx(50).cy(50).r(50).fill('#f06');
Creating Basic shapes with gySVG
Next, we will walk through how to create basic shapes with gySVG. Note, every element and attribute in an SVG file can be animated if desired.
To create a rectangle, we will make use of the
.add('rect') method. The
.height() establish the size of the rectangle while
.y() moves the shape to the appropriate position. All of these values are related to the dimensions defined in the viewBox.
const svg = gySVG().viewBox(0, 0, 100, 100).width(75).height(75); const rect = svg.add('rect').x(10).y(10).width(90).height(90).fill('#00D800');
.fill() sets the interior color for the shape, while
.stroke() sets the border color and
.stroke_width() the width of this border. Note that all colors default to black when left unspecified.
It is also possible to create rounded corners by specifying values within
To create a circle, we will make use of the
.add('circle') method, which creates a circle defined with a center point (
.cy()) and an outer radius (
.r()). All these values are determined according to the dimensions defined in the viewBox.
const svg = gySVG().viewBox(0, 0, 100, 100).width(75).height(75); const circle = svg.add('circle').cx(50).cy(50).r(50).fill('#0000D8');
.fill() method sets the interior color for the circle while the method
.stroke() can be used to set the circle border color and
.stroke_width() the border width.
const svg = gySVG().viewBox(0, 0, 100, 100).width(75).height(75); const circle = svg.add('circle').cx(50).cy(50).r(45) .fill('#D80000').stroke('#00D800').stroke_width(10);
Learn how to create other shapes like ellipses, polygons, lines, and more here.
.add('path') method is used to create an SVG path. This element represents the outline of a shape. Although all basic shapes can be created with a path element, path elements are normally reserved for more complex shapes.
The path information is described with
.d and a group of special methods, or directly with
.d(path_data). The easiest approach is to use
.d methods like
.d.L() and then build the path data step-by-step from there.
Uppercase letter methods express coordinates in absolute terms, while lowercase methods express them in relative terms from the most recently declared coordinates. Here is a short list of available methods in
gySVG () is used in the code below to create an SVG heart with
Creating gradients and patterns with gySVG
In previous examples, we saw how to make use of
.stroke() to add color to an SVG. In this section, we will consider how to make use of gradients and patterns to fill shapes.
.stroke() values with the gradient’s and pattern’s method
.url(). This method return the element’s unique id reference with the pseudo-function
There are two types of gradients that we will consider: linear and radial.
linearGradient changes color uniformly along a straight line based on each of the color points (
stop) and the transition between them. By default, the gradient is from left to right; if you need another angle (for example,
45), you can use
stop element is defined with an
.offset() to define a percentage, and
.stop_opacity() to define the color reference for that point.
The code below is used to create a circle shape SVG with a linear gradient fill.
radialGradient is very similar to
linearGradient, but in this case, the coordinates for the gradient are now circular, moving from the center to the edge.
The code below is used to create a circle shape SVG with a radial gradient fill.
pattern defines a graphic object which can be redrawn on intervals into the SVG. It has its own
.viewBox() bound reference, and its size is defined by
The behavior of width and height depends on the
.patternUnits() configuration, which, by default, is
objectBoundingBox. To proceed, we will need to configure it as
'userSpaceOnUse'. With this configuration, height and width are references to the element’s coordinate system that uses the
The code below is used to create a circle shape SVG with pattern fill:
More examples of dynamic shapes
In addition to being great for creating basic and complex shapes, gySVG can also be used to build more dynamic elements including:
This example is a very simple car racing game. Click the start button to see how it works!
Explore even more gySVG examples and documentation here.
LogRocket: Full visibility into your web apps
LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.