Capture HTML Canvas as Gif/Jpg/Png/Pdf

Capture HTML Canvas as gif/jpg/png/pdf?

Original answer was specific to a similar question. This has been revised:

const canvas = document.getElementById('mycanvas')
const img = canvas.toDataURL('image/png')

with the value in IMG you can write it out as a new Image like so:

document.getElementById('existing-image-id').src = img

or

document.write('<img src="'+img+'"/>');

Export Canvas as .gif image

This will answer your question. In short, try console.log'ing your data, and, not all browsers will support writing to a gif.

Export Canvas WITH an image AS an image (like PNG or jpg)

Do you own http://www.helpinghomelesscats.com or is your code hosted directly on that site? If not you won't be able to do this due to cross site origin policies. The best way would be to have some server side code grab the image and then serve it locally on your domain.

If you do own helpinghomelesscats.com this should work, as tested here

Live Demo

Click the canvas and view the log in order to see the response.

How do I convert a HTML canvas into a REAL picture?

Thanks for the confirmation. Please try this method, which will not hamper your css properties and give you a printable PDF file:

function print() {


// Generating PDF using HTML2Canvas
html2canvas(document.body,{
useCORS: true,
onrendered:function(canvas){
var img=canvas.toDataURL("image/png");
var imgData = canvas.toDataURL('image/png');
var imgWidth = 210;
var pageHeight = 295;
var imgHeight = canvas.height * imgWidth / canvas.width;
var heightLeft = imgHeight;

var doc = new jsPDF('p', 'mm');
var position = 0;

doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;

while (heightLeft >= 0) {
position = heightLeft - imgHeight;
doc.addPage();
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
}
doc.save('myDoc.pdf');
}
});

}


Related Topics



Leave a reply



Submit