Search code examples
javascriptsvgpaperjs

Paper JS only exporting <g> </g> element


So I create a paperjs path object and put it in a group:

let path = new paper.Path.Rectangle(originpoint, deviceWidth, deviceHeight);
let ret = new paper.Group();
ret.addChild(path);

And then I export the ret to SVG as follows:

let svg = ret.exportSVG({
            asString:true
        });

But the output of this is only coming as :

<g xmlns="http://www.w3.org/2000/svg" fill="none" fill-rule="nonzero" stroke="none" stroke-width="1" stroke-linecap="butt" stroke-linejoin="miter" stroke-miterlimit="10" stroke-dasharray="" stroke-dashoffset="0" font-family="none" font-weight="none" font-size="none" text-anchor="none" style="mix-blend-mode: normal"><path d="M0,85000v-85000h135000v85000z"/></g>

As you can notice there is no <svg> element here. How can I get the standard SVG header without having to manually splice it into the code. I'm obviously missing something because the project I am working on generates SVG's of whats displayed on the canvas with the <svg> elements with the following header:

<svg width="135mm" height="85mm" viewBox="0 0 135000 85000" xmlns="http://www.w3.org/2000/svg">

Im sure I'm missing some detail of how paper.js works, its seems like paper.js has specific objects that it puts into the svg container. Does anyone know what it is ? or What I might be doing wrong....

Thanks!


Solution

  • I am not a paper.js user or something but just playing around with the library I realized that exportSVG is inherited from paper prototype, so if you call it from current project paper.project then it seems to work as intended:

    paper.setup(new paper.Size(300, 200));
    let path = new paper.Path.Rectangle([0,0], 100, 100);
    let ret = new paper.Group();
    ret.addChild(path);
    let svg = paper.project.exportSVG({
                asString:true
            });
            console.log(svg);
    
    <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="300" height="200"><g fill="none" fill-rule="nonzero" stroke="none" stroke-width="1" stroke-linecap="butt" stroke-linejoin="miter" stroke-miterlimit="10" stroke-dasharray="" stroke-dashoffset="0" font-family="none" font-weight="none" font-size="none" text-anchor="none" style="mix-blend-mode: normal"><g><path d="M0,100v-100h100v100z"/></g></g></svg>
    

    FIDDLE: https://jsfiddle.net/ibowankenobi/juem7f80/1/

    Scroll to the bottom to see the snippet.