将画布绘制记录为动画.GIF

时间:2016-06-15 14:16:55

标签: javascript html5 canvas

我正在尝试在画布上录制一幅画图。我正在使用此库https://github.com/antimatter15/jsgif将画布输出保存为动画.GIF

对于概念证明,我使用的是纯JS画布绘图脚本 - http://zipso.net/sketchpad/sketchpad-lines.html

下面你可以找到init函数 - 我得到一个黑色图像,无法向gif添加新帧。我怎样才能解决这个问题?任何建议表示赞赏。

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())
}

1 个答案:

答案 0 :(得分:0)

你需要让事件做到那里,因为你在调用完成后没有向画布绘制任何内容,因此你会得到一个黑色图像。

逻辑应遵循

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.
}