Render HTML to an image

后端 未结 17 1801
栀梦
栀梦 2020-11-22 16:06

Is there a way to render html to image like PNG? I know that it is possible with canvas but I would like to render standard html element like div for example.

17条回答
  •  死守一世寂寞
    2020-11-22 16:18

    The only library that I got to work for Chrome, Firefox and MS Edge was rasterizeHTML. It outputs better quality that HTML2Canvas and is still supported unlike HTML2Canvas.

    Getting Element and Downloading as PNG

    var node= document.getElementById("elementId");
    var canvas = document.createElement("canvas");
    canvas.height = node.offsetHeight;
    canvas.width = node.offsetWidth;
    var name = "test.png"
    
    rasterizeHTML.drawHTML(node.outerHTML, canvas)
         .then(function (renderResult) {
                if (navigator.msSaveBlob) {
                    window.navigator.msSaveBlob(canvas.msToBlob(), name);
                } else {
                    const a = document.createElement("a");
                    document.body.appendChild(a);
                    a.style = "display: none";
                    a.href = canvas.toDataURL();
                    a.download = name;
                    a.click();
                    document.body.removeChild(a);
                }
         });
    

提交回复
热议问题