Search code examples
javascriptsvgpaperjs

Import SVG to path in paper.js returns null


Upon trying to import an SVG into the paper.js canvas, the element logs as "null".

<script src="path/to/paper-full.min.js"></script>
<canvas id="myCanvas" resize></canvas>
<script src="path/to/script.js" type="text/paperscript" canvas="myCanvas"></script>

inside script.js:

var svg = '../assets/couch.svg';

var couch = project.importSVG(svg);

console.log(couch); // returns null

I don't know why this isn't working, as this method seems to be used in solutions to different answers… -> Import svg with gradient stroke to paper.js project

Expected output of console.log would be an object (see http://paperjs.org/reference/item/#importsvg-svg where it says "Returns: Item — the newly created Paper.js item containing the converted SVG content")


Solution

  • right, it appears that you can only import and work with SVG files from the importSVG() callback. If you want to use it as an object outside the callback function, it needs to be a DOM element.

    copy and paste the content of the SVG file "inline" into your html file, append it using the fetch API or echo its contents from the backend (which is what I ended up doing), then:

    svg = document.getElementById('your-selector')
    
    var yourConvertedSVGItem = project.importSVG(svg, function() {
        svg.style.display = 'none' // hide the source image or do something else here
    })
    
    console.log(yourConvertedSVGItem)