Search code examples
kineticjsopacity

Kineticjs fillAlpha not working


Can anybody tell me or put me on the right way regarding the following problem? I want to create textbox on canvas using kineticjs. I am trying to get a text with transparent fill and with black stroke. It seems canvas is not doing anything when I try either of the following two:

  1. obj.setAttr('fillAlpha',0.1); - nothing happens
  2. obj.fillAlpha(0.1); - throws an error on canvas: Uncaught TypeError: Object # has no method 'fillAlpha'

Solution

  • To independently adjust fill opacity and stroke opacity, you need to create a group containing a stroked text object and a filled text object.

    Here's example code and a Demo: http://jsfiddle.net/m1erickson/b7qAB/

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>Prototype</title>
        <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
        <script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v5.0.1.min.js"></script>
    <style>
    body{padding:20px;}
    #container{
      border:solid 1px #ccc;
      margin-top: 10px;
      width:350px;
      height:350px;
    }
    </style>        
    <script>
    $(function(){
    
        var stage = new Kinetic.Stage({
            container: 'container',
            width: 350,
            height: 350
        });
        var layer = new Kinetic.Layer();
        stage.add(layer);
    
        var textGroup=new Kinetic.Group({
            x:10,
            y:30,
            draggable: true
        });
        layer.add(textGroup);
    
        var textFill = new Kinetic.Text({
            x:0,
            y:0,
            text:"Hello",
            fontSize:108,
            fill: 'red'
        });
        textGroup.add(textFill);
    
        var textStroke = new Kinetic.Text({
            x:0,
            y:0,
            text:"Hello",
            fontSize:108,
            stroke: 'black',
            strokeWidth: 3,
        });
        textGroup.add(textStroke);
    
        layer.draw();
    
    
        var strokeOpacity=1.00;
        var fillOpacity=1.00;
        var mode=1;
        var opacity=100;
        var delta=-1
    
        animate();
    
        function animate(){
            requestAnimationFrame(animate);
    
            if(opacity<1){
                delta=1; 
                opacity=1;
            }
            else if(opacity>100){
                opacity=100; 
                delta=-1; 
                mode=-mode;
            }
            else {
                opacity+=delta;
                if(mode==1){
                    textStroke.setOpacity(opacity/100);
                }else{
                    textFill.setOpacity(opacity/100);
                }
            }
            layer.draw();
        }
    
    }); // end $(function(){});
    
    </script>       
    </head>
    <body>
        <div id="container"></div>
    </body>
    </html>