Search code examples
jquerykineticjs

How to place the text inside the layer using kinetic js?


i am new to kineticJs & canvas

i am generating the map via kineticJs & canvas using the svg path....

map has been rendered successfully..

I need to place text center of the each layer in that canvas.

I try to achieve, but still am unable to parse the text into the layer.

Please see the jsFiddle link below.

Using this method I am generating method

var simpleText = new Kinetic.Text({
    x: path.getX(),
    y: path.getY(),
    text: key,
    fontSize: 24,
    fontFamily: 'Calibri',
    width:path.getWidth() ,
    align: 'center',    
    fill: 'white'
});

Kindly advice - js fiddle


Solution

  • This is jsfiddle: http://jsfiddle.net/edward_lee/dqhzjnut/18/

    You need to calculate bound of each path to place text center of path. Find minimum x, y and maximum x, y in path.dataArray which has svg data.

    var minX = 9999;
    var minY = 9999;
    var maxX = -1;
    var maxY = -1;
    
    path.dataArray.forEach(function(data){
        if(data.command == 'C' || data.command == 'L'){
            if(data.start.x < minX) minX = data.start.x;
            if(data.start.x > maxX) maxX = data.start.x;
            if(data.start.y < minY) minY = data.start.y;
            if(data.start.y > maxY) maxY = data.start.y;
        }
    });
    

    and then place Kinetic.Text center of path

    var simpleText = new Kinetic.Text({
        x: (minX + maxX) / 2,
        y: (minY + maxY) / 2,
        text: key,
        fontSize: 24,
        fontFamily: 'Calibri',
        align: 'center',    
        fill: '#c00'
    }); 
    

    This is a reply to comment


    To resize the canvas according to screen resolution, an event handler is required on window resize event.

    window.onresize = function(e){
        ...
    }
    

    In the handler, resize stage according to window inner size, set scale of stage, and draw map layer. I set proportional constant of scale to 1/800.

    stage.setWidth(window.innerWidth);
    stage.setHeight(window.innerHeight);
    stage.scaleX(window.innerWidth/800);
    stage.scaleY(window.innerWidth/800);
    mapLayer.draw();
    

    To change text color when mouse hover path, you can use mouseover handler attached on paths. First, you need to connect path and text to decide which text color will be changed when mouse hover a path. Kinetic.Path object do not use 'text' property, so I'll path.text to point simpleText.

    path.text = simpleText;
    

    Then change color of path.text

    path.on('mouseover', function () {
        this.setFill(bahrainMap.governorates[this.attrs.id].hoverColor);
        this.text.fill('#00cc00');
        mapLayer.draw();
    });
    

    There isn't API to set background color, so you can use css code.

    #container{
        background-color:#ccc;
    }