In the previous days, we built up from static SVG files to inline SVG and then to dynamic SVG generation using JavaScript.
Today, we take a major step toward scalable, maintainable graphics code by introducing two key libraries: svgutils.js
and svg-grid-grapher.js
.
The svgutils.js
library frees the developer from the repetitive details of creating SVG elements and setting their attributes.
Instead of manually constructing SVG markup or calling document.createElementNS
for every shape, you can use simple utility functions to create and configure SVG elements programmatically.
Building on svgutils.js
, the svg-grid-grapher.js
library provides a higher-level abstraction for simulating raster graphics.
It encapsulates the details of SVG element creation and exposes a generic interface for specifying the width, height, and virtual pixel size of your grid, as well as the color of each pixel at integer coordinates.
A key architectural point is that svg-grid-grapher.js
encapsulates svgutils.js
using generic methods.
This means that, in the future, we can swap out the underlying graphics implementation (for example, to use Canvas or WebGL) without changing the interface our code relies on.
#4caf50
, but you provide the color as three separate values.)
A virtual pixel serves as a stand-in for a physical pixel, but is intentionally larger—often spanning several real screen pixels. This makes it much easier to see and experiment with the behavior of individual "pixels" in our simulated raster grid. As we continue, this approach will be especially handy for testing and visualizing our graphics algorithms before we move on to higher resolutions or more advanced rendering techniques.
The relationship is straightforward: the physical dimensions of the SVG image are just the grid width and height multiplied by the virtual pixel size. For example, a grid of 20×15 with a virtual pixel size of 7 yields an SVG that's 140×105 pixels. This scaling lets us easily observe and interact with each virtual pixel during development.
By using these libraries, we can focus on the logic of our graphics algorithms, rather than the mechanics of SVG element creation. This abstraction is a crucial step toward more advanced rendering techniques.
svgutils.js
and svg-grid-grapher.js
SVG should be produced here on script load.