Tibor Szasz Tibor Szasz - 1 year ago 251
Javascript Question

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.

Answer Source

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

    //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;


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download