Search code examples
javascripthtmlcanvaspaperjs

How to resize a raster(image) in paper.js?


I have loaded an image using the code from the Paper.js documentation. But I would like to change the image size. I don't want to scale the image but rather set dimensions to the image. Is there a way to set width and height of an image in Paper.js?

JS

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

Solution

  • There is no such method by default in the Paper.js Raster documentation. This won't prevent you from adding your own though. You can do the following:

    /**
     * Re-scales the Raster object to the new dimensions.
     * Method added to the Raster's prototype to easily
     * call it from the raster object itself.
     */
    Raster.prototype.rescale = function(width, height) {
        this.scale(width / this.width, height / this.height);
    };
    
    var raster = new Raster({
        source: 'http://assets.paperjs.org/images/marilyn.jpg',
        position: view.center
    });
    
    raster.rescale(200, 100);
    

    Here is a codepen with a working example.