Search code examples
canvaskineticjs

Using gif image and saving


I tried to add gif image into a canvas and after adding, gif was static but when I change some other object property, i.e. Kinetic.Text();s setY() property, gif image moved to another step of an animation.

Is any way, how to to add gif image into a layer and then use

stage.toDataURL({
    callback: function(dataUrl) {
        //callback
    })
});

to save as a gif image? Or does exist any different mechanism how to achieve this effect?


Solution

  • If you want to save the first image in an animated .gif you can draw it to an offscreen canvas and then use context.getDataURL to get a dataUrl of the first image:

    Example code and a Demo: http://jsfiddle.net/m1erickson/53Jw4/

    <!doctype html>
    <html>
    <head>
    <link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
    <style>
        body{ background-color: ivory; }
        canvas{border:1px solid red;}
    </style>
    <script>
    $(function(){
    
        var canvas=document.getElementById("canvas");
        var ctx=canvas.getContext("2d");
    
        var img=new Image();
        img.crossOrigin="anonymous";
        img.onload=start;
        img.src="https://dl.dropboxusercontent.com/u/139992952/multple/animated.gif";
        function start(){
            ctx.drawImage(img,0,0);
            var url=canvas.toDataURL();
        }
    
    }); // end $(function(){});
    </script>
    </head>
    <body>
        <h4>The animated .gif in an img element</h4>
        <img src="https://dl.dropboxusercontent.com/u/139992952/multple/animated.gif"><br>
        <h4>The animated .gif drawn in a canvas element</h4>
        <canvas id="canvas" width=300 height=300></canvas>
    </body>
    </html>