the following code can be used in two modes, mode 1 will save the html code for the image, mode 2 will save the html code on the canvas.
this code works with the library: https://github.com/tsayen/dom-to-image
* "id_div" is the identifier of the html element you want to convert.
** "canvas_out" is the identifier of the div that the canvas will contain, so try this code.
function Guardardiv(id_div){ var mode = 2 // default 1 (save to image), mode 2 = save to canvas console.log("Process start"); var node = document.getElementById(id_div); // get the div that will contain the canvas var canvas_out = document.getElementById('canvas_out'); var canvas = document.createElement('canvas'); canvas.width = node.scrollWidth; canvas.height = node.scrollHeight; domtoimage.toPng(node).then(function (pngDataUrl) { var img = new Image(); img.onload = function () { var context = canvas.getContext('2d'); context.drawImage(img, 0, 0); }; if (mode == 1){ // save to image downloadURI(pngDataUrl, "salida.png"); }else if (mode == 2){ // save to canvas img.src = pngDataUrl; canvas_out.appendChild(img); } console.log("Process finish"); }); }
so if you want to save the image just add this function:
function downloadURI(uri, name) { var link = document.createElement("a"); link.download = name; link.href = uri; document.body.appendChild(link); link.click(); }
Usage example:
<html> <head> </script src="/dom-to-image.js"></script> </head> <body> <div id="container"> All content that want to transform </div> <button onclick="Guardardiv('container');">Convert<button> <div id="canvas_out"></div> </html>
Comment if this works. Comenten si les sirvio :)
Luis Villadiego Dec 08 '17 at 16:52 2017-12-08 16:52
source share