8:0 p5 SVG
A library created by zenozeng is one of the most popular ways of making SVGs with p5JS.
zenozeng / p5.js-svg
zenozeng is a coder who's put a project on GitHub that allows us to use p5js with SVGs. We can make almost anything with SVGs that we would normally make with the canvas.
It does run a bit slower than p5 normally does, but its very useful for exporting SVGs for generative design projects.
Using the zenozeng/p5 library
In your index.html file you need to import the p5-svg library after you've imported p5, add this line:
<script src="https://unpkg.com/p5.js-svg@1.5.1"></script>
Documentation is here, so make sure you check this page:
https://github.com/zenozeng/p5.js-svg
One big gotcha is that p5-svg is not compatible with the latest version of p5. So you must use a slightly older version. This is pretty easy to do however - just change the number of the p5 version. Right now its compatible with 1.6.0. Below is the full import code for p5 and p5-svg:
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.6.0/p5.js"></script>
<script src="https://unpkg.com/p5.js-svg@1.5.1"></script>
Using p5-svg in the sketch
Once you've imported p5-svg in your index.html you can tell the canvas to use SVG:
createCanvas(100, 100, SVG);
Adding SVG after your canvas dimensions will cause the sketch to be rendered as a SVG instead of an HTML canvas.
Simple p5 SVG example
See this sketch in the p5 editor: editor.p5js.org/amcc/sketches/JeR16TQz-
function setup() {
// we have imported p5-svg in index.html
// so we can use the SVG canvas below
createCanvas(400, 400, SVG);
}
function draw() {
background(255);
// make rectangles draw from the centre
rectMode(CENTER);
// turn off fills
noFill();
// draw a rectangle and a circle
circle(200, 200, 300);
rect(200, 200, 250);
// stop the sketch looping
noLoop();
}