@vim-crouwel/svg-factory
v0.1.0
Published
svg creation library built on top of svg.js
Readme
SVG Factory
A TypeScript library for creating and manipulating SVG graphics with utilities for shapes, vectors, layouts, and UI components.
Installation
npm install svg-factoryQuick Start
import { foundation, shaper, vector } from 'svg-factory';
// Create an SVG drawing board
const container = document.getElementById('svg-container');
const svg = foundation.makeDrawingBoard(container, 800, 600);
// Create a circle
const circle = shaper.circle({
db: svg,
radius: 50,
center: [400, 300, 0],
stroke: 'blue',
fill: 'lightblue'
});API Reference
Foundation
makeDrawingBoard(container, width, height)
Creates an SVG drawing board and adds it to a container element.
container(HTMLElement): The HTML element to add the SVG towidth(number): The width of the SVGheight(number): The height of the SVG- Returns: Svg drawing board
Shapes
circle(params)
Creates a circle SVG element.
params.db(Svg): The SVG container to add the circle toparams.radius(number): The radius of the circleparams.center(Vec3d): The center position [x, y, z]params.stroke(string, optional): The stroke color (default: "black")params.fill(string | Gradient, optional): The fill color or gradient (default: "none")- Returns: Circle element
polygonVertices(edges, radius, initialAngle)
Generates the vertices of a regular polygon.
edges(number): The number of edges (default: 3)radius(number): The distance from center to vertices (default: 1)initialAngle(number): The rotation angle (default: 0)- Returns: Array of vertices as [x, y] coordinates
Vector Operations
2D Vectors (vec2d)
add(a, b): Adds two 2D vectorssubtract(a, b): Subtracts one vector from anothermultiply(vector, scalar): Multiplies vector by scalardivide(vector, scalar): Divides vector by scalarmagnitude(vector): Calculates vector lengthnormalize(vector): Normalizes vector to unit lengthclone(vector): Creates a copy of the vectorapplyMatrix2(vector, matrix): Applies 2x2 matrix transformationapplyMatrix3(vector, matrix): Applies 3x3 matrix transformation
3D Vectors (vec3d)
add(a, b): Adds two 3D vectorssubtract(a, b): Subtracts one vector from anothermultiply(vector, scalar): Multiplies vector by scalardivide(vector, scalar): Divides vector by scalarmagnitude(vector): Calculates vector lengthnormalize(vector): Normalizes vector to unit lengthclone(vector): Creates a copy of the vectorapplyMatrix3(vector, matrix): Applies 3x3 matrix transformationapplyMatrix4(vector, matrix): Applies 4x4 matrix transformation
getCentroid(points)
Calculates the centroid (center point) of a set of points.
points(Vec[]): Array of points (each point is an array of numbers)- Returns: Centroid point as an array of numbers
- Throws: Error when no points provided or points have different dimensions
Matrix Transformations
2D Matrices (matrix2)
identity(): Creates 2x2 identity matrixrotate(angle): Creates 2D rotation matrix (angle in radians)scale(x, y): Creates 2D scale matrixmultiply(a, b): Multiplies two 2x2 matrices
3D Matrices (matrix3)
identity(): Creates 3x3 identity matrixtranslate(x, y): Creates 2D translation matrixrotate(angle): Creates 2D rotation matrix (angle in radians)scale(x, y): Creates 2D scale matrixshear(x, y): Creates shear/skew matrixmultiply(a, b): Multiplies two 3x3 matricesinverse(matrix): Calculates matrix inversetranspose(matrix): Transposes matrix
4D Matrices (matrix4)
identity(): Creates 4x4 identity matrixtranslate(x, y, z): Creates 3D translation matrixrotateX(angle): Rotates around X axis (angle in radians)rotateY(angle): Rotates around Y axis (angle in radians)rotateZ(angle): Rotates around Z axis (angle in radians)scale(x, y, z): Creates 3D scale matrixmultiply(a, b): Multiplies two 4x4 matricestranspose(matrix): Transposes matrixlookAt(eye, target, up): Creates view matrixperspective(fov, aspect, near, far): Creates perspective projection matrixorthographic(left, right, bottom, top, near, far): Creates orthographic projection matrix
Layout
grid(columns, rows, drawingFunction)
Executes a drawing function for each cell in a grid.
columns(number): Number of columns in the gridrows(number): Number of rows in the griddrawingFunction(function): Function to execute for each cell, receives (column, row) indices
UI Components
makeSvgDownloadButton(props)
Creates a download button for SVG content.
props.svg(Svg): The SVG element to downloadprops.fileName(string): The name for the downloaded fileprops.container(HTMLElement | null): Container to add the button to (optional)
ImageProcessor
Class for processing image uploads and extracting pixel data.
Constructor
onLoadCallback(function): Callback function called when image loads, receives width and height
Methods
getColorAt(x, y): Gets the color of a pixel at specified coordinates- Returns: RGBA color object
{r, g, b, a}or null
- Returns: RGBA color object
Properties
width: Image widthheight: Image height
Utilities
map(value, start1, stop1, start2, stop2)
Maps a value from one range to another.
value(number): The input value to mapstart1(number): Lower bound of original rangestop1(number): Upper bound of original rangestart2(number): Lower bound of target rangestop2(number): Upper bound of target range- Returns: Mapped value
makeElm(tag, attributes)
Creates an HTML element with specified attributes.
tag(string): The HTML tag nameattributes(object): Object containing element attributes- Returns: HTML element
rgbaToColorString(color)
Converts an RGBA color object to a string representation.
color(object): RGBA color object with properties r, g, b, a- Returns: String representation in RGBA format
Type Definitions
type Vec2d = [number, number];
type Vec3d = [number, number, number];Examples
Creating a Grid of Circles
import { foundation, shaper, layout } from 'svg-factory';
const container = document.getElementById('app');
const svg = foundation.makeDrawingBoard(container, 600, 400);
layout.grid(10, 6, (col, row) => {
shaper.circle({
db: svg,
radius: 20,
center: [col * 60 + 30, row * 60 + 30, 0],
fill: `hsl(${col * 36}, 70%, 50%)`
});
});Vector Manipulation
import { vector } from 'svg-factory';
const v1 = [3, 4];
const v2 = [1, 2];
const sum = vector.vec2d.add(v1, v2); // [4, 6]
const magnitude = vector.vec2d.magnitude(v1); // 5
const normalized = vector.vec2d.normalize(v1); // [0.6, 0.8]Image Color Sampling
import { ui, color } from 'svg-factory';
const processor = new ui.ImageProcessor((width, height) => {
console.log(`Image loaded: ${width}x${height}`);
// Sample color at center of image
const centerColor = processor.getColorAt(width/2, height/2);
const colorString = color.rgbaToColorString(centerColor);
console.log(`Center color: ${colorString}`);
});Creating 3D Geometry
Create 3D objects and project them to 2D SVG with perspective. This example creates a rotating cube:
import { foundation, vector } from 'svg-factory';
// Setup
const svg = foundation.makeDrawingBoard(document.body, 600, 600);
const cubeGroup = svg.group();
// Define cube vertices (8 corners)
const cubeSize = 100;
const vertices = [
[-1, -1, -1], [1, -1, -1], [1, 1, -1], [-1, 1, -1], // back face
[-1, -1, 1], [1, -1, 1], [1, 1, 1], [-1, 1, 1] // front face
].map(v => vector.vec3d.multiply(v, cubeSize));
// Define edges (pairs of vertex indices)
const edges = [
[0,1], [1,2], [2,3], [3,0], // back face
[4,5], [5,6], [6,7], [7,4], // front face
[0,4], [1,5], [2,6], [3,7] // connecting edges
];
// Simple perspective projection
function project(point) {
const distance = 400;
const scale = distance / (distance + point[2]);
return [
point[0] * scale + 300, // center X
point[1] * scale + 300 // center Y
];
}
// Animation
let angle = 0;
function animate() {
cubeGroup.clear();
// Create rotation matrices
const rotX = vector.matrix4.rotateX(angle * 0.7);
const rotY = vector.matrix4.rotateY(angle);
const rotZ = vector.matrix4.rotateZ(angle * 0.5);
// Combine rotations
const rotation = vector.matrix4.multiply(
rotX,
vector.matrix4.multiply(rotY, rotZ)
);
// Transform and draw
const projected = vertices.map(v => {
const rotated = vector.vec3d.applyMatrix4(v, rotation);
return project(rotated);
});
// Draw edges
edges.forEach(([i, j]) => {
cubeGroup
.line(projected[i][0], projected[i][1], projected[j][0], projected[j][1])
.stroke({ width: 2, color: '#333' });
});
angle += 0.02;
requestAnimationFrame(animate);
}
animate();Key concepts:
- Use
Vec3dtype[x, y, z]for 3D points - Apply 3D transformations with
matrix4.rotateX/Y/Z(),matrix4.translate(), etc. - Combine transformations with
matrix4.multiply() - Transform points with
vec3d.applyMatrix4(point, matrix) - Project 3D to 2D:
scale = distance / (distance + z) - Draw the projected 2D points as SVG
