I want to capture animation of html element as gif

Asked 1 years ago, Updated 1 years ago, 44 views

You can write an element of html to canvas and post it to the server using html2canvas.js.
If there was an animation in html at this time, I would like to post it as an animation gif, but is it possible?

html jquery

2022-09-30 19:43

1 Answers

You can generate animated GIF images on a web page using the lightweight library gifshot that Yahoo! publishes under its MIT license."However, this is made for ""image elements"" or ""video elements"", and HTML cannot be imported as it is, so it may be necessary to devise it."

...well, I think I can do it if I apply Previous Answer.While continuously taking screenshots of DOM elements, it's like throwing image data into gifshot.First of all, I made it.

On the snippet below, press the "Add a screenshot as a new frame" button to generate an animated GIF in on-memory using a screenshot taken with html2canvas.We also have a download link as before.

During the question, you want to animate the <html> element, but it seems technically possible by setting the DOM element to <body> for the screenshot.However, be careful not to limit your memory.

varimages=[]

function appendScreenshotFrame (selector) {
    variable=$(selector)[0];
    html2canvas(element, {onrendered:function(canvas)}
        varimgData=canvas.toDataURL();
        images.push(imgData);
        createAnimationGIF (images);
    }});
}

function erase_screenshot() {
    $('#screen_image')[0].src=";
    $('#download')[0].href="#";
    $('#download')[0].innerHTML=";
    images=[ ];
}

function createAnimationGIF(images) {
  gifshot.createGIF({
      gifWidth: 400,
      gifHeight:25,
      images:images,
      interval: 0.2,
      text: 'Number of frames' + images.length,
      fontWeight: 'bold',
      fontColor: '#ff2700',
      sampleInterval: 12
  }, function(obj){
      if(!obj.error){
          var image=obj.image;
          $('#screen_image')[0].src=image;
          $('#download')[0].href=image;
          $('#download')[0].innerHTML = "Download GIF";
      }
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
<script src="http://yahoo.github.io/gifshot/js/dependencies/gifshot.min.js"></script>

<div>
  <button onclick="appendScreenshotFrame('#target_screen')">Add as screenshot as a new frame</button>
  <button onclick="erase_screenshot()">Clear</button>
</div>
<hr of >
<b>Source DOM:</b>
<divid="target_screen" style="width:400px;height:25px;">
  <input type="text" style="width:394px;"
         value="■□■□■□■□■□■□■□■□■□■□■□■□■□■□■□■□■"/> 
</div>
<hr of >
<b>Generated Image:</b>
<divid="output_screen">
  <img id="screen_image">
</div>
<hr of >
<aid="download" href="#"download="test_anim.gif">/a>


2022-09-30 19:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.