TriFu
TriFu

Reputation: 641

kineticjs add text to shape

I want to add text inside of the shape, and then have the shape be draggable.

Here is a fiddle showing the text, and the shape being draggable...but I have no idea how to add the text inside of the shape.

http://jsfiddle.net/sJpdz/

    <script src="kinetic-v4.3.3.min.js"></script>
    <script>
        var stage = new Kinetic.Stage({
            container: 'container',
            width: 500,
            height: 500
        });

        var layer = new Kinetic.Layer();

        var rect = new Kinetic.Rect({
            x: 239,
            y: 75,
            width: 100,
            height: 50,
            fill: 'green',
            stroke: 'black',
            strokeWidth: 4,
            draggable: true
        });

        var simpleText = new Kinetic.Text({
            x: stage.getWidth() / 2,
            y: 15,
            text: 'Simple Text',
            fontSize: 30,
            fontFamily: 'Calibri',
            textFill: 'green',
            stroke: 'gray',
            fill: 'white'
        });
        layer.add(simpleText);
        // add the shape to the layer
        layer.add(rect);

        // add the layer to the stage
        stage.add(layer);
    </script>

The only way I can think of is just making 2 separate layers overlap and grouping them together. However this seems rather cumbersome of a process and I was hoping for a more elegant solution.

Thanks,

Upvotes: 1

Views: 2994

Answers (1)

Ioana Grozav
Ioana Grozav

Reputation: 133

var stage = new Kinetic.Stage({
            container: 'container',
            width: 500,
            height: 500
        });

var layer = new Kinetic.Layer({
 draggable: true
});

        var rect = new Kinetic.Rect({
            x: 239,
            y: 75,
            width: 100,
            height: 50,
            fill: 'green',
            stroke: 'black',
            strokeWidth: 4,

        });

        var simpleText = new Kinetic.Text({
            x: rect.getX(),
            y: rect.getY(),
            text: 'Simple Text',
            fontSize: 24,
            fontFamily: 'Calibri',
            width:rect.getWidth() ,
            align: 'center',    
            fill: 'white'
        });
     layer.add(rect);
        layer.add(simpleText);
        // add the shape to the layer


        // add the layer to the stage
        stage.add(layer);

Upvotes: 4

Related Questions