Skip to content

An easy lightweight vanilla JavaScript SVG manager, fill/stroke manipulator, and external loader with caching.

License

Notifications You must be signed in to change notification settings

hewiefreeman/SvgFactoryJS

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

59 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

SvgFactoryJS

A fast, easy, and lightweight vanilla Javascript SVG API for manipulating, managing, and externally loading SVGs with caching.

Main Features:

  • Load and inject SVGs straight into your HTML from a URL
  • Use SvgFactoryJS on any SVGs, even those not injected by SvgFactoryJS
  • Methods to change the fills and stokes of entire SVGs or individual shapes with ease
  • Generates a viewBox for SVGs without one for easy scaling
  • Keeps track of all your SVGs
  • And plenty of more helpful features!

Installing

At the moment, the only way to install SvgFactoryJS is to download SvgFactoryJs.min.js and put it in one of your project folders. Then you can import it to your HTML page with (of course replacing your_project_folder with your actual path):

<script type="text/javascript" src="your_project_folder/SvgFactoryJS.min.js"></script>

That's it!


Quick Start

Setting up...

Make a global SvgFactory reference:

var svgFactory = new SvgFactory();

You may also provide a String parameter for SvgFactory() to set it's unit type (for example: in, mm, em, pt, etc):

var svgFactory = new SvgFactory("em");

Or you can set the unit type with setUnitType():

svgFactory.setUnitType("px");

Loading...

To load an external SVG, first you need to get the Element reference of the container you'd like to inject it into. Then pass the container's Element reference and a URL into SvgFactory.load():

//...
var container = document.getElementById("container_id");
svgFactory.load(container, "the_url.svg");

It's easy to make a listener for when the SVG is done loading. Just pass the name of the callback function as the third parameter in SvgFactory.load():

//...
svgFactory.load(container, "the_url.svg", callbackFunction);

function callbackFunction(e){
    //code for when the SVG is finished loading...
}

The parameter for callbackFunction is the SvgFactoryImage that was created along with the injected SVG. To learn more about the SvgFactoryImage type, see the Documentation or keep reading for a quick explanation.

You can also pass additional parameters to SvgFactory.load():

//...
svgFactory.load(destination, url, onComplete, cache, hideForLoad, svgID, width, height, fills, strokes);

If you have an SVG on your site that has not been injected using SvgFactoryJS, not to worry! You can still use SvgFactoryJS to manipulate it as long as you have the ID or Element reference to the SVG:

//...
//get the SVG by it's ID:
var svg1 = svgFactory.get("svg_id");

//or by it's SVG Element reference:
var svg2 = svgFactory.get(svg2Element);

SvgFactory.get() returns an SvgFactoryImage. You can use an SvgFactoryImage to access all the features to manipulate the underlying SVG with SvgFactoryJS. This makes it fast and easy to remove SVG elements (and it's garbage) from your site, or set the SVG's fills, strokes, size, or ID:

//...
var svg = svgFactory.get("theSvg");
svg.setFills("#123456");
svg.setStrokes([["#000000", 0.5]]);
svg.setSize(125, 352);
svg.setId("new_svg_id");
svg.remove();

Resizing...

The methods for resizing an SVG are SvgFactoryImage.setSize(), SvgFactoryImage.setWidth(), and SvgFactoryImage.setHeight(). The method SvgFactoryImage.setSize() takes in the parameters (width, height). Width and height can both either be a String or a Number. A Number will use whatever unitType is set in SvgFactory, and a String will use whatever unitType is provided in the String:

//...
var svg = svgFactory.get("my_svg");
svgFactory.setUnitType("px");
svg.setSize("100%", 50);
// Now svg's width is 100%, and height is 50px

The methods SvgFactoryImage.setWidth() and SvgFactoryImage.setHeight() work the same way, but only take one parameter:

//...
var svg = svgFactory.get("my_svg");
svgFactory.setUnitType("em");
svg.setWidth(79);
svg.setHeight("50pt");
// Now svg's width is 79em, and height is 50pt

If you want to access the SVGElement of an SvgFactoryImage to (for instance) change the SVG's style properties or add attributes to it, use SvgFactoryImage.element:

//...
var svg = svgFactory.get("my_svg");
var svg_element = svg.element;
svg_element.style.top = "40px";
svg_element.setAttribute("class", "my_svg_css_class");

Setting fills and strokes...

SvgFactoryJS uses an Array to define a fill or a stroke:

  • Fill: [color, opacity]
  • Stroke: [color, opacity, width, miter-limit, dash-array, line-cap, line-join]

The color is the only required property for either a fill or a stroke. Any other property can be set to null to skip it, but the fill or stroke Array must be in the same order shown above. You can also cut the Array short of properties starting from the end, as long as you maintain the order, and the Array starts with color.

A fill takes a color (String) and the opacity (Number) of the color. You can also supply an RGBA color, and take the opacity out of the Array or set it to null. Same goes for a stroke, but it also can take in a few other properties. You can think of strokes as outlines, or just lines in general:

If your SVG has multiple shapes, you can change the fill of all shapes in the same line by making an Array of fills:

//...
svg.setFills([["#7c2af9", 1], ["rgb(120, 65, 200)", 0.6], ["rgba(74, 179, 7, 0.5)", 0.3]]);

Same goes for the SVG's strokes:

//...
svg.setStrokes([["#7c2af9", 1, 10], ["rgb(120, 65, 200)", 0.6, 3, null, [3, 5], "round", "bevel"], ["rgba(74, 179, 7, 0.5)"]]);

Note: The fills and strokes are applied in the same order that each shape appears in the raw SVG file.

Warning: If you pass a String to setFills() or setStrokes() for an SVG with more than one shape, the color will be applied to all the shapes in the SVG. Also, if you pass an Array that doesn't have as many fills or strokes as the SVG has shapes, it will cycle through the provided fills or strokes.

You can get an SVG's individual shape by it's id with SvgFactoryImage.getElementById():

//...
var squareShape = the_svg.getElementById("square");

You can use this shape reference to change it's fill or stroke with SvgFactory.setFillOf() and SvgFactory.setStrokeOf():

//...
svgFactory.setFillOf(squareShape, ["#ffffff", 0.45]);
svgFactory.setStrokeOf(squareShape, ["#000000", 1, 5, null, [5, 10]]);

Documentation (In progress)

Class SvgFactory(unitType)

Initializes an instance of SvgFactory.
Parameter Description
unitType Optional: (String) Defines the type of dimensional units the library will use for sizing. Accepted unit types are "px", "%", "em", "ex", "cm", "mm", "in", "pt", and "pc". Default is "px" (pixel value).

SvgFactory Fields:

Field Description
unitType (String) Defines the type of dimensional units the library will use for sizing. If you wish to manually set this field, only set to "px", "%", "em", "ex", "cm", "mm", "in", "pt", or "pc".
loadedSvgs (Array) An Array of all the instances of SvgFactoryImage that SvgFactoryJS has created. READ ONLY

SvgFactory Methods:

Method Description
load(destination, url, onComplete, cache, hideForLoad, svgID, width, height, color)

Loads an SVG from the url into the destination.

  • destination (Element): The DOM element to inject the loaded SVG into.
  • url (String): The URL path for the SVG image to load.
  • onComplete (Function) Optional: The function to call when the SVG is done loading.
  • cache (Boolean) Optional: Whether or not to use the cache. Default is true.
  • hideForLoad (Boolean) Optional: Whether or not to make the destination invisible while loading the SVG. destination is shown again only after the SVG has loaded and all modifications (provided by load()) have been applied. Default is false.
  • svgID (String) Optional: The ID to be given to the injected SVG tag.
  • width (Number) Optional: The width to be given to the injected SVG tag. Negative numbers are handled as percentage, otherwise SvgFactory.unitType is used.
  • height (Number) Optional: The height to be given to the injected SVG tag. Negative numbers are handled as percentage, otherwise SvgFactory.unitType is used.
  • fills (String or [[String, Number], ]) Optional: See SvgFactoryImage.setFills() for a detailed explanation of setting the fills of an SVG.
  • strokes (String or [[String, Number], ]) Optional: See SvgFactoryImage.setStrokes() for a detailed explanation of setting the strokes of an SVG.
get(idOrElement)

Returns the SvgFactoryImage for an SVG. Can use the SVG's ID as a String, or the SVG's Element reference.

  • idOrElement (String or Element): The SVG's ID or Element reference you wish to get the SvgFactoryImage for.
setUnitType(unitType)

Sets the unitType of SvgFactoryJS.

  • unitType (String): The type of dimensional units the library will use for sizing. Can only set to "px", "%", "em", "ex", "cm", "mm", "in", "pt", or "pc".

Class SvgFactoryImage()

There is an instance of SvgFactoryImage for every SVG injected and retrieved with SvgFactoryJS. You can think of an SvgFactoryImage as an actual SVG image, since you will use SvgFactoryImage to maniplulate an SVG instead of it's Element.

SvgFactoryImage Fields:

Field Description
element (SVGElement) The SVG DOM Element of the SvgFactoryImage
fills (Array of Array [[], ]) An Array of fills for the SVG. A fill is an Array defined like so [color, opacity]. A null property means it has not been defined.

  • color (String): The color of the fill
  • opacity (Number): The opacity of the fill
strokes (Array of Array [[], ]) An Array of strokes for the SVG. A stroke is an Array defined like so [color, opacity, width, miterlimit, dasharray, linecap, linejoin]. A null property means it has not been defined.

  • color (String): The color of the stroke
  • opacity (Number): The opacity of the stroke
  • width (Number): The width of the stroke
  • miterlimit (Number): The miterlimit of the stroke
  • dasharray (Array): The dasharray of the stroke
  • linecap (String): The linecap of the stroke
  • linejoin (String): The linejoin of the stroke
url (String) The URL of the SVG image (null for objects that haven't been loaded with SvgFactory.load() method)
id (String) The ID of the SvgFactoryImage and underlying SVGElement
width (String) The width of the SVGElement with it's unitType included. EG: "150px"
height (String) The height of the SVGElement with it's unitType included. EG: "340in"

SvgFactoryImage Methods:

Method Description
setSize(width, height)

Sets the width and height of the SVG Element and SvgFactoryImage using the unitType of SvgFactory. Providing a String will override the unitType of SvgFactory.

  • width (Number or String): The desired width
  • height (Number or String): The desired height
setWidth(width)

Sets the width of the SVG Element and SvgFactoryImage using the unitType of SvgFactory. Providing a String will override the unitType of SvgFactory.

  • width (Number): The desired width
setHeight(height)

Sets the height of the SVG Element and SvgFactoryImage using the unitType of SvgFactory. Providing a String will override the unitType of SvgFactory.

  • height (Number or String): The desired height
setFills(fills)

Sets the fill color and opacity of all Elements in the SVG.

EG: [["blue", 1], ["red", 0.2], ["green", 0.8]]

  • fills (Array[Fill, ...]): An Array of Fill. A Fill is also an Array structured like so: [fill-color, fill-opacity]


MIT License

Copyright (c) 2018 Dominique Debergue

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

About

An easy lightweight vanilla JavaScript SVG manager, fill/stroke manipulator, and external loader with caching.

Topics

Resources

License

Code of conduct

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published