Search code examples
javascriptpaperjs

Parse.js onResize() with rectangle


I'm very new to Paper.js and not that familiar with JS (be happy, these are some easy rep points!) I want to center a rectangle in a canvas and I succeed. The problem is that I'd like that this rectangle stays in the middle when onResize is called and the doc didn't explain that very well or, at least, I didn't find something consistant.

Here is my code:

createYearBar(1983, 2015);

function createYearBar(yearStart, yearEnd){
    var yearsToDraw = (yearEnd - yearStart);
    var topLeftX = view.center.x * 0.2;
    var topRightX = view.center.x * 1.8;
    var barSize = topRightX - topLeftX;
    var perYear = (barSize)/yearsToDraw;
    var topleft = new Point(topLeftX, 20);
    var size = new Size(barSize, 30);
    var rect = new Rectangle(topleft, size);
    var barPath = new Path.Rectangle(rect);
    barPath.strokeColor = 'black';
    barPath.fillColor = 'black'
}

So it draws a rectangle like I want but it does nothing when I resize. I do not get why because this view.center.x should come from the framework.

It is a bit better if I add:

function onResize(event) {
    createYearBar(1983, 2015);
}

because my bar can get bigger but not smaller because it just adds bars over the already existing ones.

My question is:

Do I need to that manually and delete and recreate the bar manually or did I miss something trivial (I assume that I missed something!)?


Solution

  • You're missing a couple of things, but you are correct in your guess: the easiest thing to do is destroy and recreate a bar on each resize event.

    view.center just returns a regular coordinate when you call it. If a view is 300x400, view.center will return a new Point object at [150, 200]. It is not a dynamic point that updates the positions of objects when you resize the window.

    The problem is that you aren't removing the barPath object when you resize the view. It's much easier to do this if your function returns an object instead of creating one anonymously inside a function scope:

    var barPath = createYearBar(1983, 2015);
    
    function createYearBar(yearStart, yearEnd){
        var yearsToDraw = (yearEnd - yearStart);
        var topLeftX = view.center.x * 0.2;
        var topRightX = view.center.x * 1.8;
        var barSize = topRightX - topLeftX;
        var perYear = (barSize)/yearsToDraw;
        var topleft = new Point(topLeftX, 20);
        var size = new Size(barSize, 30);
        var rect = new Rectangle(topleft, size);
        barPath = new Path.Rectangle(rect);
        barPath.strokeColor = 'black';
        barPath.fillColor = 'black';
        return barPath;
    }
    
    function onResize(event) {
        barPath.remove();
        barPath = createYearBar(1983, 2015);
    }