Security News
Node.js EOL Versions CVE Dubbed the "Worst CVE of the Year" by Security Experts
Critics call the Node.js EOL CVE a misuse of the system, sparking debate over CVE standards and the growing noise in vulnerability databases.
Scalable Vector JavaScript. A very light object-oriented library to help generative artists working with SVG.
SvJs is a very light object-oriented library to help generative artists working with SVG.
It is a thin wrapper over the real SVG spec with some useful generative functions included. This keeps its footprint extremely small whilst maintaining fidelity to the SVG spec.
It is inspired by the gySVG library, but takes a different approach under the hood and is more geared towards generative art.
To install via npm:
npm install svjs
You can then import it either via the dist
folder (minified, with all modules included) or import just the modules you want via the src
folder.
To install via the CDN link, ensure your script tag has type="module"
declared. Then import it as follows (replace latest
with a specific version if you prefer):
// Import just the core functionality.
import { SvJs } from 'https://cdn.jsdelivr.net/npm/svjs@latest/dist/svjs.min.js';
// Import the full library.
import { SvJs, Gen, Noise } from 'https://cdn.jsdelivr.net/npm/svjs@latest/dist/svjs.min.js';
The SvJs
class located at src/sv.js
contains the core SVG-related functionality.
new SvJs()
Class constructor. Creates a new SVG element.
Throws an error if the argument passed isn't a valid SVG element.
Paramaters:
Returns: itself.
Chainable: yes.
// To create a parent SVG element, no arguments are required.
const svg = new SvJs();
// To create a specific element, use the element name as the argument.
const rect = new SvJs('rect');
addEventListener()
An alias of the DOM addEventListener method.
Paramaters:
Returns: itself.
Chainable: yes.
addTo()
Add (or append) one element to another.
Paramaters:
Returns: itself.
Chainable: yes.
// Appends the main svg to an element with the id of 'container'.
svg.addTo(document.getElementById('container'));
// Appends the rect element to the parent SVG.
rect.addTo(svg);
animate()
Animate an element using the Web Animations API.
Paramaters:
Returns: itself.
Chainable: yes.
// Set up the keyframes (in this case an object of arrays).
let keyframes = {
transform: [
'rotate(0deg) scale(1, 1)',
'rotate(180deg) scale(0.5, 1.5)',
'rotate(360deg) scale(1, 1)'
]
};
// Set up the options.
let options = {
duration: 5000,
iterations: Infinity
};
// Apply the animation to an SvJs element.
circle.animate(keyframes, options);
content()
Inserts content within an element. Useful for textual and style elements.
Paramaters:
Returns: itself.
Chainable: yes.
// Add content to a text element.
let text = svg.create('text');
text.content('Hello SVG World.');
// Use content to apply styles to all paths.
svg.create('style').content(`
path {
fill: none;
stroke-width: 0.75;
stroke-linecap: round;
}`
);
create()
This is a shortcut method to create and append a child element. It is essentially the same as calling a new SvJs(element)
and afterwards calling addTo(parentElement)
.
Throws an error if the argument passed isn't a valid SVG element.
Paramaters:
Returns: the created child element.
Chainable: yes.
// This is an alternative way of creating the rect and appending it to the svg.
const rect = svg.create('rect');
createCurve()
Creates a smooth, open bezier curve from an array of points.
Parameters:
[[x,y], [x,y]...]
points.Returns: itself (the created path element).
Chainable: yes.
// Given a viewBox of '0 0 1000 1000', the below creates a closed circular curve.
const pts = [
[500, 300],
[300, 500],
[500, 700],
[700, 500],
];
const path = svg.createCurve(pts, 1.66);
createFilter()
Creates a filter and appends it to the defs element.
Parameters:
Returns: itself (the created filter element).
Chainable: yes.
// Initialise the filter.
let filter = svg.createFilter('blur');
// Create a blur effect.
filter.create('feGaussianBlur').set({ stdDeviation: 10 });
// Apply the filter to a SvJs element called circle.
circle.set({ filter: 'url(#blur)' });
createGradient()
Shortcut method to create a gradient and append it to the defs element. If will create a defs element if it doesn't already exist.
Can only be called by the parent SVG element. Throws error otherwise.
Parameters:
Returns: itself (the created gradient element).
Chainable: yes.
// Create a sunset-coloured gradient and apply it to a rect.
const grad = svg.createGradient('sunset', 'linear', ['red', 'orange', 'yellow'], 90);
rect.set({ fill: 'url(#sunset)' });
createPattern()
A shortcut method to create a pattern and append it to the defs element. If will create a defs element if it doesn't already exist. The actual pattern elements can then be added as children.
Can only be called by the parent SVG element. Throws error otherwise.
Parameters:
Returns: itself (the created pattern element).
Chainable: yes.
// Create a pattern consisting of two rect elements.
const pattern = svg.createPattern('myPattern', 100, 100);
pattern.create('rect').set({ x: 0, y: 0, width: 50, height: 50, fill: '#333' });
pattern.create('rect').set({ x: 50, y: 50, width: 50, height: 50, fill: '#666' });
rect.set({ fill: 'url(#myPattern)' });
delete()
Removes the element.
Parameters: none.
Returns: undefined.
Chainable: no.
get()
Fetches the value of the attribute, which is supplied as the argument.
Parameters:
Returns: The attribute's value.
Chainable: no.
// Get the fill value of our rect element.
rect.get('fill');
getCentre()
Get a given element's centre { x, y } co-ordinates. Particularly useful for groups.
Parameters: none.
Returns: {object} the centre.x and centre.y co-ordinates.
moveTo()
Move an element to a desired position with respect to its centre. Particularly useful for groups.
Paramaters:
Returns: itself.
Chainable: yes.
// Move a rect to the centre of a 1000 x 1000 viewBox.
rect.moveTo(500, 500);
rotate()
Rotate an element around a specified origin point (the element centre by default).
Paramaters:
Returns: itself.
Chainable: yes.
// Rotate a rect by 90 degrees around its own centre.
rect.rotate(90);
save()
Saves the generated <svg>
markup as a downloadable file.
Parameters: none.
Returns: undefined.
Chainable: no.
// Call the save method by pressing the 's' key.
document.addEventListener('keydown', (event) => {
if (event.code === 'KeyS') {
svg.save();
}
});
scale()
Scale an element by a desired proportion.
The element is scaled from its centre, which involves an additional translation.
Paramaters:
Returns: itself.
Chainable: yes.
// Scale a rect to double its original size.
rect.scale(2);
// Scale a rect differntly along the x and y axis.
rect.scale(1.5, 2.5);
set()
Set the attribute value(s) of an SVG element.
For attributes that contain a dash (e.g. stroke-width), use an underscore instead (stroke_width).
Parameters:
Returns: The original element.
Chainable: yes.
// Create a circle element and set its attributes.
const circle = svg.create('circle');
circle.set({
cx: 500,
cy: 500,
r: 250,
fill: 'crimson',
stroke: 'gold',
stroke_width: 5
});
trackCursor()
Update the cursorX
and cursorY
properties on the main SVG element. These are set to null by default; calling trackCursor()
activates the event listeners needed to update them.
Can only be called by the parent SVG element. Throws error otherwise.
Accurate cursor tracking is done via matrix transformation (normal cursor tracking using clientX
and clientY
values don't work with SVG). Compatible with touch devices.
Values of cursorX
and cursorY
are relative to the viewBox
.
Parameters: none.
Returns: itself (the parent SVG element).
Chainable: yes.
// Create an svg element and activate cursor tracking.
const svg = new SvJs();
svg.set({ viewBox: '0 0 1000 1000' }).trackCursor();
console.log(svg.cursorX, svg.cursorY);
-> 210, 502
The generative functions can be imported via the optional Gen
module. They are especially useful for generative art.
import { Gen } from '../../svjs/src/index.js';
chance()
Return true if the supplied % is higher than a randomised %. If two arguments supplied, they are interpreted as odds.
Parameters:
Returns: {boolean} true or false.
// The below returns true 60% of the time.
Gen.chance(60);
// There is a 7 to 2 chance of this returning true.
Gen.chance(7, 2);
constrain()
Constrains (or clamps) a value between a minimum and maximum value.
Parameters:
Returns: {number} The constrained number.
Gen.constrain(50, 5, 10);
-> 10
Gen.constrain(2, 5, 10);
-> 5
Gen.constrain(6, 5, 10);
-> 6
dist()
Calculates the distance between two points using the Pythagorean theorem.
Parameters:
Returns: {number} The distance between (x1, y1) and (x2, y2).
Gen.dist(10, 12, 40, 50);
-> 48.41487374764082
gaussian()
Gets a random number based on the Box-Muller gaussian transform.
By default, it typically returns results within a range of -3 to +3.
Parameters:
Returns: {number} The random gaussian.
// By default, uses a mean of 0 and sigma of 1.
Gen.gaussian();
-> 1.4712050780435197
// Specify a mean of 5 and sigma of 2.
Gen.gaussian(5, 2);
-> 7.169042426896327
interp()
Interpolates linearly between two values. Returns the midway point (0.5) by default.
Parameters:
Returns: {number} interpolated value.
Gen.interp(5, 10);
-> 7.5
Gen.interp(5, 10, 0.4);
-> 7
Gen.interp(5.25, 10.95);
-> 8.1
map()
Re-maps a number from one range to another.
Parameters:
Returns: {number} The remapped number.
Gen.map(5, 0, 10, 0, 100);
-> 50
pareto()
Gets a random number based on the pareto power law distribution (80-20 rule).
Parameters:
Returns: {number} The random pareto number.
// Return a pareto-distributed integer, not less than 20.
Gen.pareto(20, false);
-> 32
random()
Gets a random number between a minimum and maximum value, or picks a random item from an array.
Without parameters, it will return a float between 0 and 1.
Parameters:
Returns: {number} The random number or array item.
// Return a float between 0 and 1.
Gen.random();
-> 0.5682831319665758
// Return a float between 50 and 100.
Gen.random(50, 100);
-> 87.98188644344106
// Return a whole number between 10 and 20.
Gen.random(10, 20, false);
-> 17
// Return a random item from an array.
let rainbow = ['red', 'yellow', 'pink', 'green', 'purple', 'orange', 'blue'];
Gen.random(rainbow);
-> 'purple'
This small module is an implementation of Ken Perlin's noise algorithm in 2D.
It consists of a constructor and a single get()
method.
new Noise()
Class constructor. Creates an instance of the Noise class.
Paramaters: none.
// Create an instance of the Noise class.
const noise = new Noise();
get()
Get the noise value at the specified co-ordinates.
Parameters:
Returns: {number} the noise value (float between -1 and 1).
// Instantiate a Noise instance and fetch the noise value at the specified co-ordinates.
const n = new Noise();
const value = n.get(999);
FAQs
Scalable Vector JavaScript. A very light object-oriented library to help generative artists working with SVG.
The npm package svjs receives a total of 7 weekly downloads. As such, svjs popularity was classified as not popular.
We found that svjs demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Critics call the Node.js EOL CVE a misuse of the system, sparking debate over CVE standards and the growing noise in vulnerability databases.
Security News
cURL and Go security teams are publicly rejecting CVSS as flawed for assessing vulnerabilities and are calling for more accurate, context-aware approaches.
Security News
Bun 1.2 enhances its JavaScript runtime with 90% Node.js compatibility, built-in S3 and Postgres support, HTML Imports, and faster, cloud-first performance.