60
svgpen provides a canvas-like API for working with Scalable Vector Graphics (SVG). It aims to simplify SVG manipulation by offering a more programmatic approach, similar to the HTML5 Canvas API, but generating SVG elements instead of rasterized images. This allows developers to create and manipulate SVG graphics using JavaScript with less verbosity than raw SVG DOM manipulation.
Canvas-like API: Offers familiar methods like fillRect, fillEllipse, etc., abstracting the complexities of document.createElementNS.
Real DOM Output: Generates actual SVG elements that can be styled with CSS, animated, or exported.
Efficient Updates: Utilizes methods like updateCanvas to modify SVG attributes directly, enabling smooth animations without full redraws, unlike traditional canvas.
Lightweight: Zero dependencies, with tree-shakeable ESM and UMD builds available.
Programmability: Empowers developers to focus on the logic of graphic creation by abstracting raw SVG commands.
Install via npm:
npm i @js_cipher/svgpen
Create a root element in your HTML:
<div id="root" width="400" height="300"></div>
Then, use the SVGRoot class in your JavaScript:
import { SVGRoot } from '@js_cipher/svgpen'; const svg = new SVGRoot(root, 300, 300); svg.fillRect(10, 10, 100, 50, 'red', 'black'); svg.fillEllipse(200, 50, 40, 20, '#3b82f6'); svg.renderText('Hello SVG', 10, 120, '#111', 16);
new SVG(root, w, h): Initializes the SVG canvas.
fillRect(x, y, w, h, fill?, stroke?): Draws a rectangle.
fillEllipse(cx, cy, r, fill?, stroke?): Draws an ellipse.
plotLine(x1, y1, x2, y2, stroke, strokeWidth?): Draws a line.
polygon(points, fill?, stroke?, strokeWidth?): Draws a polygon.
path(d, fill?, stroke?, strokeWidth?): Draws an SVG path.
renderText(text, x, y, fill?, fontSize?): Draws text.
updateCanvas(element, attribute, newValue): Updates specific attributes of an SVG element for animations.
The project is open source under the MIT license, and contributions via Pull Requests are welcome.
Built with