0

I am trying to record a gif of drawing on canvas. I am using this library https://github.com/antimatter15/jsgif to save canvas output as animated .GIF

For a proof of concept I am using a pure JS canvas drawing script - http://zipso.net/sketchpad/sketchpad-lines.html

Below you can find the init function - I get a black image and cannot add new frames to gif. How can I fix this? Any advice appreciated.

function init() {
    // Get the specific canvas element from the HTML document
    canvas = document.getElementById('sketchpad');

    // If the browser supports the canvas tag, get the 2d drawing context for this canvas
    if (canvas.getContext)
        ctx = canvas.getContext('2d');

        var encoder = new GIFEncoder();
        encoder.setRepeat(0);
        encoder.setDelay(100); //go to next frame every n milliseconds
        encoder.start();


    // Check that we have a valid context to draw on/with before adding event handlers
    if (ctx) {



        // React to mouse events on the canvas, and mouseup on the entire document
        canvas.addEventListener('mousedown', sketchpad_mouseDown, false);
        canvas.addEventListener('mousemove', sketchpad_mouseMove, false);
        window.addEventListener('mouseup', sketchpad_mouseUp, false);

        // React to touch events on the canvas
        canvas.addEventListener('touchstart', sketchpad_touchStart, false);
        canvas.addEventListener('touchend', sketchpad_touchEnd, false);
        canvas.addEventListener('touchmove', sketchpad_touchMove, false);
    }




      encoder.addFrame(ctx);
        encoder.finish();


     document.getElementById('image').src = 'data:image/gif;base64,'+encode64(encoder.stream().getData())
}
Vonder
  • 4,033
  • 15
  • 44
  • 61
  • I'm not sure but I think the `encode.finish()` and `encoder.stream().getData()` parts should out of your init function... like when you finish the recording ;-) – Kaiido Jun 15 '16 at 14:22
  • see also [Capture HTML canvas as GIF/JPG/PNG/PDF?](https://stackoverflow.com/questions/923885/capture-html-canvas-as-gif-jpg-png-pdf) – milahu Mar 06 '23 at 09:39

1 Answers1

1

You need to let the events do there thing as you have not drawn anything to the canvas when you call finish, therefor you get a black image.

The logic should follow

Start/Setup function(){
  setUp Canvas
  addEvent handlers
  setup encoder.
  return  // You must exit or the event handlers will not fire
}

Event Handlers(){
  for each event
  render to canvas
  encoder.addFrame(); // adds the new frame
}

Save Function(){ // when you have added what you want then you can call finish
  encoder.finish()
  download.
} 
Blindman67
  • 51,134
  • 11
  • 73
  • 136