Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

P5js SVG Export

I have a P5js sketch which creates a font that users can type anything they want. I want to allow the user to download an svg/pdf (vector) version of their result. As of now I succeeded to have them download a .jpg version using the save order and saving a shot of my screen. Any ideas?

like image 614
Naty Avatar asked Feb 28 '16 10:02

Naty


3 Answers

That's an old thread, but maybe my solution will be useful to someone. To export vector graphics in P5js to SVG file, first I use SVG renderer from p5.svg.js library - this will put svg element directly into HTML document. Exporting is to extract the content of that element (by outerHTML property) and save it to a file (like in this post). So, for example, your "Save as SVG" button callback function may look like this:

function downloadSvg()
{
    let svgElement = document.getElementsByTagName('svg')[0];
    let svg = svgElement.outerHTML;
    let file = new Blob([svg], { type: 'plain/text' });
    let a = document.createElement("a"), url = URL.createObjectURL(file);

    a.href = url;
    a.download = 'exported.svg';    
    document.body.appendChild(a);
    a.click();

    setTimeout(function() 
    {
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);  
    }, 0); 
}
like image 109
arek Avatar answered Nov 06 '22 20:11

arek


From googling "p5.js svg", there doesn't seem to be a built-in way to work with SVG images in p5.js.

However, that search returns several promising results:

Here is a GitHub issue with a discussion about working with SVGs in p5.js.

Here is a project that attempts to add SVG support to p5.js:

The main goal of p5.SVG is to provide a SVG runtime for p5.js, so that we can draw using p5's powerful API in <svg>, save things to svg file and manipulating existing SVG file without rasterization.

Another discussion that links to two more SVG libraries.

The p5.SVG library sounds especially promising. I suggest you try something out and post an MCVE if you get stuck.

like image 3
Kevin Workman Avatar answered Nov 06 '22 20:11

Kevin Workman


A new package called canvas-sketch seems to solve this issue. They have a wealth of examples for p5.js as well.

const canvasSketch = require('canvas-sketch')
const p5 = require('p5')

const settings = {
  p5: { p5 },
  // Turn on a render loop
  animate: true,
}

canvasSketch(() => {
  // Return a renderer, which is like p5.js 'draw' function
  return ({ p5, time, width, height }) => {
    // Draw with p5.js things
    p5.background(0)
    p5.fill(255)
    p5.noStroke()

    const anim = p5.sin(time - p5.PI / 2) * 0.5 + 0.5
    p5.rect(0, 0, width * anim, height)
  };
}, settings)

If you use p5 globally, there's also an example for that called animated-p5.js

like image 1
kano Avatar answered Nov 06 '22 20:11

kano