Search code examples
kineticjs

Set group width depending on content


I want to use KineticJs, and I am writing a function which is like position:absolute;right:...px for the element Group() with kineticJS, I do like this :

right : function(dist){
        this.x(250-this.width()-dist);
    }

(250 is the container width) But the width of the group element is 0, even if I use group.add(image). I would like to know if there is a way to have the width of the Group, in this case it will be the width of the image in the group. Regards


Solution

  • You could create a function that resizes the group based on its children's sizes:

    Example code and a Demo: http://jsfiddle.net/m1erickson/3bz2L/

    function resizeGroupToContents(group){
        var width=0;
        var height=0; 
        group.getChildren().each(function(node){
            var right=node.x()+node.width();
            if(right>width){width=right;}
            var bottom=node.y()+node.height();
            if(bottom>height){height=bottom;}
        });
        group.width(width);
        group.height(height);
        layer.draw();
    }