Search code examples
html5-canvaskineticjs

KineticJS change color of text onclick


I am working on KineticJS(Latest version) and i have issue regarding change text color which drawn by drawFunc() shape object.

1)Here is the code of Shpae Object.

var sampleText = new Kinetic.Shape({
    x:380,
    y:700,
    drawFunc: function(context) {
    context.beginPath();          
       var x = 0;
       var y = 0;
       var text = 'Sample Text';
       context.setAttr("font", '15pt Calibri');
       context.setAttr('fillStyle','black');          
       context.fillText(text, x, y)
       context.closePath();
       // KineticJS specific context method
       context.fillStrokeShape(this);
    },  
    id:"sampleText"
});

2)I want to change color of "sample text" on click event which is written using core html5 code (context object).

colorTabViews.on('click', function (e) {
    sampleText.sceneFunc(function(context) {
        context.beginPath();
        //how can i get text which already displayed in shape object("Sample text")?
        //or to change color of "sample text"
        context.setAttr('fillStyle','green');

        context.closePath();
        context.fillStrokeShape(this);
    });
    verticalText.draw();
});

But issue is ,it removes whole text nothing displayed instead of just changing "sample text" color.

Please advice either get text filled by context.fillText() function or alternate way that i can change text color on particular event.

Thanks for your time and consideration in advance. -Naitik


Solution

  • To programatically change fillStyle inside a Kinetic.Shape

    Attach a fill property to your shape object and reference your fill property inside the Kinetic.Shape:

    var sampleText = new Kinetic.Shape({
        x:10,
        y:15,
        sceneFunc: function(context) {
          context.beginPath();          
          var x = 0;
           var y = 0;
           var text = 'Sample Text';
           context.setAttr("font", '15pt Calibri');
           context.setAttr('fillStyle',this.myFillStyle);          
           context.fillText(text, x, y)
           context.closePath();
           // KineticJS specific context method
           context.fillStrokeShape(this);
        },  
        id:"sampleText",
        fill:"blue"
    });
    
    // add a property to sampleText that's used in its sceneFunc
    sampleText.myFillStyle="black";
    

    Then you can change that fill property in your click handler:

    colorTabViews.on('click', function (e) {
        sampleText.myFillStyle="red";
        verticalText.draw();
    });