Export SVG file from p5.js?

The following works on my Mac:

let x, y, r, g, b, z, i;

function setup() {
  createCanvas(1920, 1080, SVG);
  background(0);
}

function draw() {
  r = random(0, 255);
  g = random(0, 255);
  b = random(0, 255);
  x = random(width);
  y = random(height);
  z = random(0, 15);
  i = random(255);
  noStroke();
  fill(r, g, b, 100);
  //circle(mouseX, mouseY, z);
  circle(x, y, z);
}

function mousePressed() {
  background(i);
}

function keyPressed() {
  save("myImg.svg"); // give file name
  print("saved svg");
  noLoop(); // we just want to export once
}

Note the addition of ‘SVG’ to createCanvas() as well as the addition of the following line of code to the index.html:

<script src=“https://unpkg.com/p5.js-svg@1.3.1”></script>

Output:

The file will open in a browser (Safari or Chrome).

2 Likes