使用jQuery/JavaScript将Div转换为图片

6
我正在尝试使用html2canvas库将div转换为图像。我已经尝试过,但没有成功,无法将整个div转换为图像,图像中缺少拖动器。 网址https://www.makethatvape.com/ejuicecalc/ 使用的代码如下:
html2canvas($("#widget")).then(function(canvas) {
   bimg = canvas.toDataURL();  // by default png
});

那么,有什么办法可以克服这个问题吗?我试着使用html2canvas,它可以将文本和CSS div转换为画布。


无法接受编辑...这很糟糕,新用户应该接受对他们的问题进行编辑,具有2k经验的用户可能不需要这个功能。 - user889030
2个回答

8

试试这个

<div id="copyDiv"></div>

    var element = $("#widget"); // global variable
    var getCanvas; // global variable
    
    html2canvas(element, {
             onrendered: function (canvas) {
                    $("#copyDiv").append(canvas);
                    getCanvas = canvas;
                 }
      });

注意:如果HTML标记包含图像标签,则对于某些浏览器,上述代码将无法创建其图像。要使其工作,您需要使用2个参数,即allowTaintuseCORS
示例代码:
html2canvas(document.getElementById("html-content-holder"), {
            allowTaint: true, useCORS: true
        }).then(function (canvas) {
            var anchorTag = document.createElement("a");
            document.body.appendChild(anchorTag);
            document.getElementById("previewImg").appendChild(canvas);
            anchorTag.download = "filename.jpg";
            anchorTag.href = canvas.toDataURL();
            anchorTag.target = '_blank';
            anchorTag.click();
        });

详细文章:使用jQuery/Javascript将HTML转换为图像,并提供实时演示


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接