tibewww tibewww - 2 years ago 530
Javascript Question

html2canvas , save render canvas as a gif instead of a png?

I'm using html2canvas to save a snapshot from the webcam as an image.

However, it save only in png, I'm trying to save it as a gif, but can not find out how to do this

So far this is my function:

renderCanvasImage: function(){
setTimeout(function () {

// Add image with Quote to Canvas (hidden).
html2canvas($('.snap'), {
onrendered: function (canvas) {
document.body.appendChild(canvas).id = 'hidden';
var canvas = document.getElementById('hidden');

var image = new Image();
//Create a new Image with url
image.src = canvas.toDataURL("image/.png");

// Look at URI only and assign to localStorage
imageURI = image.src;
localStorage.setItem('image', imageURI);

//****TODO better removal*/
$('#cameraContainer, .wrapperInfo').hide();

$('#result a, #result img').fadeOut(100).remove();

//Send Data to DB

//PopUp Message
}, 1000);


I tried to replace the following:

image.src = canvas.toDataURL("image/.png");

By jpg of gif, but it doesn't change anything.... any tips to make this work will be amazing !!

Thanks a lot !!

Answer Source

You said in the comments above that you've got it working, however I still feel the need to tell you that the supported mime types of toDataUrl depend on the browser.

You can test it here https://jsfiddle.net/v91y0zqr/

Here's a visual example with even more mime types: http://kangax.github.io/jstests/toDataUrl_mime_type_test/

All browsers I've tested (Firefox, Chrome, Opera, IE) did support image/png and image/jpeg

Additionally, Chrome could export image/webp

Additionally, Firefox could export image/bmp

Results may differ for you.

So while in theory canvas.toDataURL("image/gif"); should create a GIF image, the browser may still decide to create a PNG (it's the default fallback).

You can read more about toDataUrl here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download