Search code examples
javascriptsvgpaperjs

Paper.js - exporting of Raster


Running the following code in paper.js library

var raster = new paper.Raster({
    source: 'http://assets.paperjs.org/images/marilyn.jpg',
    position: paper.view.center
});

raster.exportSVG()

is resulting in:

<image x="101" y="224" width="0" height="0" xlink:href="data:," 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"></image>

and as you can see:

xlink:href="data:,"

instead of containing the included image.

Is the usage correct? how should I do an export for rasters?


Solution

  • you are facing 2 problems here:

    1 - You are trying to export data from an image which is not loaded yet.
    Browser HTML requests being asynchronous, you have to wait for image to be loaded before trying to work with it.
    It is done by providing a callback.

    2 - You will then encounter another problem which is related to CORS.
    The image being stored on a different server than yours, image data usage is by default prevented for security reasons.
    So you have 2 solutions fo this:

    a - store the image on the same server as the script:

    // create Raster with local path to your image
    var raster = new Raster('./marilyn.jpg', paper.view.center);
    
    // use PaperJS built-in callback to wait for loading
    raster.onLoad = function ()
    {
        // once image is loaded
        // you can do what you want with the raster
        console.log('image loaded, SVG = ', raster.exportSVG());
    };
    

    b - make sure remote server allows CORS and add CORS attribute when loading the image:

    // create image
    var image = new Image;
    
    // add CORS attribute
    image.crossOrigin = 'Anonymous';
    
    // set remote source
    image.src = 'http://assets.paperjs.org/images/marilyn.jpg';
    
    // wait for image to be loaded
    image.addEventListener('load', function ()
    {
        // once image is loaded
        // create Raster with image element
        var raster = new Raster(image, paper.view.center);
    
        // now you can do what you want with the raster
        console.log('image loaded, SVG = ', raster.exportSVG());
    });
    

    Edit

    There is actually another simpler solution for CORS using only Raster crossOrigin property.

    var raster = new Raster({
        crossOrigin: 'anonymous',
        source: 'http://assets.paperjs.org/images/marilyn.jpg'
    });