Export SVG file from p5.js?

Hello,

I am brand new to p5.js having only reached video #13 from the Coding Train. I’m already having fun creating things and now I would like to save what the canvas looks like into a .svg file.

Is there an “easy way” :slight_smile: to do this? Asking because when I searched the forum I found code to insert from another post but I keep getting errors ;(

Here is my working project with the code I tried:

THANK YOU for any help!

Hello, @dirka, and welcome to the Processing Foundation Forum!

The reason for the errors is that you have included some Python code in your p5.js script, for example this function definition:

def setup():
    global svg_output

    size(500, 500)
    svg_output = createGraphics(width, height, SVG, "file.svg")

Hello Javagar, thank you for the welcome and for the reply!

Ok I did not know that was Python. I just now deleted that part of the code but still it does not work.

Was that even the right code to have at the bottom of my editor to export an SVG file? Is there a better place I can look for the proper p5.js svg export code?

(sidenote: I am using the web browser as my editor)

Thank you!

I’ve seen examples of code that uses a p5.svg.js library, but have been unsuccessful in getting any of those examples to work. They seem to either produce errors or corrupted .svg output. In fact, it’s not clear that the library is maintained. Perhaps someone else reading this can provide us with information about that.

If you perform a search regarding that library and find an example that actually works, please let us know.

1 Like

Hi @dirka,

So that you or anyone else interested can try to get them to work, below are two links to p5.js sketches that use the p5.svg.js library, and attempt to export .svg files. Both are offered in the p5.js online editor.

The first one does export what should be an .svg file, but I cannot display it as an image, and believe it is corrupted:

The second one results in the following error message:

ReferenceError: SVG is not defined
    at /sketch.js:9:26

I am using Chrome on a MacBook Air.

If anyone is able to get either one to work, please let us know, and specify what operating system and browser you are using.

1 Like

ReferenceError: SVG is not defined

You have to have the following line of code in index.html:

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

Which then yields this output.
svg

For some reason it only wants to open in a word processing app (Atom) which reveals lots of lines of data, in contradistinction to the first method which has only sparse data. It will open in either Safari or Chrome browsers but is a small image; not sure if that is what is intended or it is only a thumbnail. I also tried to import it into the Photos.app but it complains that it can’t read the metadata. I checked the latter in one of my own apps and there is indeed metadata which is shown below.

MetaData: 
_kMDItemDisplayNameWithExtensions      = “mySVG.svg”
com_apple_metadata_modtime             = 682494077.1811185
kMDItemContentCreationDate             = 2022-08-18 05:41:17 +0000
kMDItemContentCreationDate_Ranking     = 2022-08-18 00:00:00 +0000
kMDItemContentModificationDate         = 2022-08-18 05:41:17 +0000
kMDItemContentModificationDate_Ranking = 2022-08-18 00:00:00 +0000
kMDItemContentType                     = “public.svg-image”
kMDItemContentTypeTree                 = (
    “public.svg-image”,
    “public.image”,
    “public.data”,
    “public.item”,
    “public.content”,
    “public.xml”,
    “public.text”
)
kMDItemDateAdded                       = 2022-08-18 05:42:31 +0000
kMDItemDateAdded_Ranking               = 2022-08-18 00:00:00 +0000
kMDItemDisplayName                     = “mySVG.svg”
kMDItemDocumentIdentifier              = 0
kMDItemFSContentChangeDate             = 2022-08-18 05:41:17 +0000
kMDItemFSCreationDate                  = 2022-08-18 05:41:17 +0000
kMDItemFSCreatorCode                   = “”
kMDItemFSFinderFlags                   = 0
kMDItemFSHasCustomIcon                 = (null)
kMDItemFSInvisible                     = 0
kMDItemFSIsExtensionHidden             = 0
kMDItemFSIsStationery                  = (null)
kMDItemFSLabel                         = 0
kMDItemFSName                          = “mySVG.svg”
kMDItemFSNodeCount                     = (null)
kMDItemFSOwnerGroupID                  = 20
kMDItemFSOwnerUserID                   = 501
kMDItemFSSize                          = 22764
kMDItemFSTypeCode                      = “”
kMDItemInterestingDate_Ranking         = 2022-08-18 00:00:00 +0000
kMDItemKind                            = “SVG document”
kMDItemLastUsedDate                    = 2022-08-18 05:44:33 +0000
kMDItemLastUsedDate_Ranking            = 2022-08-18 00:00:00 +0000
kMDItemLogicalSize                     = 22764
kMDItemPhysicalSize                    = 24576
kMDItemUseCount                        = 3
kMDItemUsedDates                       = (
    “2022-08-18 05:00:00 +0000”
)

I am unfamiliar with the .svg format and am unclear about what advantages there are to using it.

2 Likes

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

@svan Thank you Svan for taking the time to help and for sending this over. I think I have more to learn as I am still getting 2 errors ;(

1 – I can’t see any of the design (the colored dots) it’s just blank when I view the file in Chrome

2 – I am able to create an SVG files but it is just blank with an error “This XML file does not appear to have any style information associated with it. The document tree is shown below.”

Google your error message to find possible reasons. May be a browser problem.

Hi all -
I am also a new Processing user, trying to get SVG exported from p5.js and finding it confusing.

I copied the code from @svan, pasted it in the online editor, and executed it. It created a download of a myImage.png (even though the specification in the code was for an svg) - and I got a bunch of errors in the console (duplicated below.)

I have managed to export a functional SVG from the Java version of Processing - but struggling with p5.js. Thanks for any help or insight.

🌸 p5.js says: [sketch.js, line 4] It seems that you may have accidentally written "SVG".
You may have meant one of the following: 
▶️ save() (http://p5js.org/reference/#/p5/save)
▶️ set() (http://p5js.org/reference/#/p5/set)
▶️ log() (http://p5js.org/reference/#/p5/log)
▶️ mag() (http://p5js.org/reference/#/p5/mag)
▶️ sin() (http://p5js.org/reference/#/p5/sin)
▶️ str() (http://p5js.org/reference/#/p5/str)
▶️ sq() (http://p5js.org/reference/#/p5/sq) 
ReferenceError: SVG is not defined
Error: [object Arguments]is not a valid color representation.

🌸 p5.js says: [p5.js, line 64684] color() was expecting Number for the first parameter, received an empty variable instead. If not intentional, this is often a problem with scope.

+ More info: https://p5js.org/examples/data-variable-scope.html (http://p5js.org/reference/#/p5/color) 

🌸 p5.js says: [sketch.js, line 23] An error with message "[object Arguments]is not a valid color representation." occurred inside the p5js library when background was called. If not stated otherwise, it might be an issue with the arguments passed to background. (http://p5js.org/reference/#/p5/background) 
saved svg 
Error: [object Arguments]is not a valid color representation.

🌸 p5.js says: [sketch.js, line 23] An error with message "[object Arguments]is not a valid color representation." occurred inside the p5js library when background was called. If not stated otherwise, it might be an issue with the arguments passed to background. (http://p5js.org/reference/#/p5/background) 
 <script src=“[https://unpkg.com/p5.js-svg@1.3.1 ]”></script>
  1. Error message says it doesn’t know what ‘SVG’ is.
  2. Did you do both of the things suggested in the answer?
  3. What Browser and which operating system are you using?

If you still have problems, please post the index.html file and source code so that we can see what you tried.

1 Like

Hi Svan -
I did copy your code exactly, so I have the addition of ‘SVG’ to createCanvas().
I am using Firefox on OS 10.14.
Here is the full index.html file.

<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.7.0/p5.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.7.0/addons/p5.sound.min.js"></script>
       <script src=“[https://unpkg.com/p5.js-svg@1.3.1 ]”></script>
    <link rel="stylesheet" type="text/css" href="style.css">
    <meta charset="utf-8" />
  </head>
  <body>
    <main>
    </main>
    <script src="sketch.js"></script>
  </body>
</html>

My index.html looks like this:

<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/addons/p5.sound.min.js"></script>
    <script src="https://unpkg.com/p5.js-svg@1.3.1"></script>
    <link rel="stylesheet" type="text/css" href="style.css">
    <meta charset="utf-8" />

  </head>
  <body>
    <main>
    </main>
    <script src="sketch.js"></script>
  </body>
</html>

Delete the brackets on your svg script. Your script has src =“[…]”. Needs to be just src=“…” Also that trailing quotation is blue not red. Could be a curly quote if you copy/pasted it. Delete the last quotation and reinsert it off of your keyboard. Both quotation characters should look the same and be the same red color.

If that fails, any way to try it on Safari or Chrome?
.

1 Like

Thanks, I think that was it!