Search code examples
canvascolorskineticjstransition

Circle color transition


I have a simple script concisting drawing a circle:

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

var layer = new Kinetic.Layer();

var circle = new Kinetic.Circle({
    x: stage.getWidth() / 2,
    y: stage.getHeight() / 2,
    radius: 70,
    fill: 'red'
});

layer.add(circle);    
stage.add(layer);

What I'd like to do is to transition color of this circle from red to blue in the course of 5 seconds (for example). Is there any way to achieve that?


Solution

  • You can use a tween to change the color of your circle:

        var tween = new Kinetic.Tween({
            node: circle,
            fillR:0,
            fillG:0,
            fillB:255,
            duration:5
        });
        tween.play();
    

    enter image description here enter image description here enter image description here

    Here’s code and a Fiddle: http://jsfiddle.net/m1erickson/5PHTZ/

    <!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-v4.5.5.min.js"></script>
    
    <style>
    #container{
      border:solid 1px #ccc;
      margin-top: 10px;
      width:400px;
      height:400px;
    }
    </style>        
    <script>
    $(function(){
    
        var stage = new Kinetic.Stage({
            container: 'container',
            width: 400,
            height: 400
        });
        var layer = new Kinetic.Layer();
        stage.add(layer);
    
        var circle = new Kinetic.Circle({
            x: stage.getWidth() / 2,
            y: stage.getHeight() / 2,
            radius: 70,
            fill: 'red'
        });
        layer.add(circle);
    
        layer.draw();
    
        document.getElementById('recolor').addEventListener('click', function() {
            var tween = new Kinetic.Tween({
                node: circle,
                fillR:0,
                fillG:0,
                fillB:255,
                duration:5
            });
            tween.play();
        }, false);
    
    
    
    
    }); // end $(function(){});
    
    </script>       
    </head>
    
    <body>
        <button id="recolor">Recolor</button>
        <div id="container"></div>
    </body>
    </html>