1

i make a gif canvas with multiple picture, now i want to export it but canvas is not export into gif its only export into png format my code is `

                var c_img = new Konva.Image({
                        image: imageObj,
                        width: 600,
                        height: 600,
                        name: 'rect',
                        draggable: true,
                        id: filename,
                        keepRatio: true,
                        enabledAnchors: [
                          'top-left',
                          'top-right',
                          'bottom-left',
                          'bottom-right',
                        ],
                    });
                    layer.add(c_img);                                 
                    var dataURL = document.querySelector('canvas').toDataURL('image/gif');`
jawad
  • 13
  • 6
  • Is there a specific reason you require exporting as a gif? Is the intention for the output to be animated? – Rory McCrossan Aug 02 '22 at 12:50
  • Basically i want to edit an image , an image contains 5 images and there is a gif one of them so when i merge each images using konva layers then i need to get final result as a gif image – jawad Aug 03 '22 at 06:49

1 Answers1

2

Canvas element doesn't support exporting into GIF. You have to use external library for that task. There are many tools available. For the demo, I used gifshot.

Using Konva you can generate frames, by exporting every frame as image. Then use these images as input for gif library.

var width = window.innerWidth / 2;
var height = window.innerHeight / 2;

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

var layer = new Konva.Layer();

var circle = new Konva.Circle({
  x: stage.width() / 2,
  y: stage.height() / 2,
  radius: 70,
  fill: 'red',
  stroke: 'black',
  strokeWidth: 4,
});

// add the shape to the layer
layer.add(circle);

// add the layer to the stage
stage.add(layer);

const frames = [];

for(var i = 0; i < 10; i++) {
  circle.fill(Konva.Util.getRandomColor());
  frames.push(layer.toDataURL());
}

gifshot.createGIF({
    gifWidth: stage.width(),
    gifHeight: stage.height(),
    images: frames,
    interval: 0.4,
    numFrames: 10,
    frameDuration: 1,
    sampleInterval: 10,
    numWorkers: 2
}, function (obj) {
    if (!obj.error) {
        var image = obj.image, animatedImage = document.createElement('img');
        animatedImage.src = image;
        document.body.appendChild(animatedImage);
    }
});
<script src="https://unpkg.com/gifshot@0.4.5/dist/gifshot.js"></script>
<script src="https://unpkg.com/konva@8.3.5/konva.min.js"></script>

<div id="container"></div>
lavrton
  • 18,973
  • 4
  • 30
  • 63