Search code examples
javascriptcanvaspaperjs

Resize rectangle in Paper.js


I have a very ordinary rectangle created in Paper.js and I'd like to resize it, but I can't find any obvious ways to do it.

var rect = new Rectangle([0, 0],[width,height]);
rect.center = mousePoint;
var path = new Path.Rectangle(rect, 4);
path.fillColor = fillColor;
path.meta = fillColor;

There's a scale transformation method, but it's not really for mouse interaction and my goal is to create a handle that can resize a component.


Solution

  • You can calculate the scaling by dividing the intended width/height of your rectangle with the current width/height of your rectangle.

    Then you can use that scaling 'coefficient' to apply the scaling.

    Based on your code above, you can get the current width/height of your rectangle by using: rect.bounds.width and rect.bounds.height

    Here's a function you can use

    var rectangle = new Shape.Rectangle({
        from: [0, 0],
        to: [100, 50],
        fillColor: 'red'
    });
    
    
    function resizeDimensions(elem,width,height){
        //calc scale coefficients and store current position
        var scaleX = width/elem.bounds.width;
        var scaleY = height/elem.bounds.height;
        var prevPos = new Point(elem.bounds.x,elem.bounds.y);
    
        //apply calc scaling
        elem.scale(scaleX,scaleY);
    
        //reposition the elem to previous pos(scaling moves the elem so we reset it's position);
        var newPos = prevPos + new Point(elem.bounds.width/2,elem.bounds.height/2);
        elem.position = newPos;
    }
    
    
    resizeDimensions(rectangle,300,200)
    

    And here's the Sketch for it.

    Be aware that the above function will also reposition the element at it's previous position but it will use top-left positioning. Paper.js uses the element's center to position them so I'm clarifying this so it doesn't cause confusion