ericdrowell / KineticJS

KineticJS is an HTML5 Canvas JavaScript framework that extends the 2d context by enabling canvas interactivity for desktop and mobile applications.
http://www.kineticjs.com
3.98k stars 752 forks source link

Group.cache() bug #1008

Open pronebird opened 10 years ago

pronebird commented 10 years ago

Hi,

I am trying to use cache() on group of shapes and it doesn't work properly, everything gets shifted in the right bottom corner.

My code detects bounds of shapes in group and caches everything within this bounds. Calculated bounds are correct, I tested by adding Kinetic.Rect.

I am not sure if it is important, but shapes have offset set and cached when added to group.

function cacheGroup(group) {
    var children = group.getChildren().toArray();
    var min = {}, max = {};

    if(!children.length) {
        return;
    }

    _.forEach(children, function (child) {
        var pos = child.getPosition();
        var size = child.getSize();
        var maxX = pos.x + size.width;
        var maxY = pos.y + size.height;

        // min X
        if(!min.x || pos.x < min.x) { min.x = pos.x; }
        // min Y
        if(!min.y || pos.y < min.y) { min.y = pos.y; }
        // max X
        if(!max.x || maxX > max.x) { max.x = maxX; }
        // max Y
        if(!max.y || maxY > max.y) { max.y = maxY; }
    }, this);

    var options = {
        x: min.x,
        y: min.y,
        width: max.x - min.x,
        height: max.y - min.y,
        drawBorder: true
    };

    // cache node
    group.cache(options);

    // restore node's position
    group.setPosition(min);
};

I suppose I hit the same bug here I reported earlier: https://github.com/ericdrowell/KineticJS/issues/1006