简体   繁体   English

使用 html2canvas 将 div 捕获到图像中

[英]capture div into image using html2canvas

I'm trying to capture a div into an image using html2canvas我正在尝试使用html2canvas将 div 捕获到图像中

I have read some similar question here like我在这里读过一些类似的问题

How to upload a screenshot using html2canvas?如何使用 html2canvas 上传屏幕截图?

create screenshot of web page using html2canvas (unable to initialize properly)使用 html2canvas 创建 web 页面的屏幕截图(无法正确初始化)


I have tried the code我试过代码

canvasRecord = $('#div').html2canvas(); 
dataURL = canvasRecord.toDataURL("image/png");

and the canvasRecord will be undefined after .html2canvas() called调用.html2canvas()canvasRecord将是undefined


and also this还有这个

$('#div').html2canvas({
      onrendered: function (canvas) {
           var img = canvas.toDataURL()
           window.open(img);
      } 
});

browser gives some (48 to be exact) similar errors like:浏览器给出了一些(准确地说是 48 个)类似的错误,例如:

GET http://html2canvas.appspot.com/?url=https%3A%2F%2Fmts1.googleapis.com%2Fvt%…%26z%3D12%26s%3DGalileo%26style%3Dapi%257Csmartmaps&callback=html2canvas_1 404 (Not Found) 

BTW, I'm using v0.34 and I have added the reference file html2canvas.min.js and jquery.plugin.html2canvas.js顺便说一句,我使用的是 v0.34,我添加了参考文件html2canvas.min.jsjquery.plugin.html2canvas.js

How can I convert the div into canvas in order to capture the image.如何将div转换为canvas以捕获图像。

EDIT on 26/Mar/2013 2013 年 3 月 26 日编辑

I found Joel's example works.我找到了Joel 的示例作品。

But unfortunately when Google map embedded in my app, there will be errors.但不幸的是,当谷歌 map 嵌入我的应用程序时,会出现错误。

<html>
<head>
<style type="text/css">
div#testdiv
{
    height:200px;
    width:200px;
    background:#222;
}
div#map_canvas
{
    height: 500px;
    width: 800px;
    position: absolute !important;
    left: 500px;
    top: 0;
}
</style>
 <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false"></script>
<script type="text/javascript" src="html2canvas.min.js"></script>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script language="javascript">
$(window).load(function(){
     var mapOptions = {
        backgroundColor: '#fff',
        center: new google.maps.LatLng(1.355, 103.815),
        overviewMapControl: true,
        overviewMapControlOptions: { opened: false },
        mapTypeControl: true,
        mapTypeControlOptions: { position: google.maps.ControlPosition.TOP_LEFT, style: google.maps.MapTypeControlStyle.DROPDOWN_MENU },
        panControlOptions: { position: google.maps.ControlPosition.RIGHT_CENTER },
        zoomControlOptions: { position: google.maps.ControlPosition.RIGHT_CENTER },
        streetViewControlOptions: { position: google.maps.ControlPosition.RIGHT_CENTER },
        disableDoubleClickZoom: true,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        minZoom: 1,
        zoom: 12
    };
    map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);

    $('#load').click(function(){

            html2canvas($('#testdiv'), {
                onrendered: function (canvas) {
                    var img = canvas.toDataURL("image/png")
                    window.open(img);
                }
            });

    });
});
</script>
</head>
<body>
<div id="testdiv">
</div>
<div id="map_canvas"></div>
<input type="button" value="Save" id="load"/>
</body>
</html>

I ran into the same type of error you described, but mine was due to the dom not being completely ready to go.我遇到了你描述的相同类型的错误,但我的错误是由于 dom 没有完全准备好。 I tested with both jQuery pulling the div and also getElementById just to make sure there wasn't something strange with the jQuery selector.我用 jQuery 拉取 div 和 getElementById 进行了测试,只是为了确保 jQuery 选择器没有什么奇怪的东西。 Below is an example that works in Chrome:下面是一个适用于 Chrome 的示例:

<html>
<head>
<style type="text/css">
div {
    height: 50px;
    width: 50px;
    background-color: #2C7CC3;
}
</style>
<script type="text/javascript" src="html2canvas.js"></script>
<script type="text/javascript" src="jquery-1.9.1.js"></script>
<script language="javascript">
$(document).ready(function() {
//var testdiv = document.getElementById("testdiv");
    html2canvas($("#testdiv"), {
        onrendered: function(canvas) {
            // canvas is the final rendered <canvas> element
            var myImage = canvas.toDataURL("image/png");
            window.open(myImage);
        }
    });
});
</script>
</head>
<body>
<div id="testdiv">
</div>
</body>
</html>

If you just want to have screenshot of a div, you can do it like this如果你只是想有一个 div 的截图,你可以这样做

html2canvas($('#div'), {
  onrendered: function(canvas) {
    var img = canvas.toDataURL()
    window.open(img);
  }
});

you can try this code to capture a div When the div is very wide or offset relative to the screen您可以尝试使用此代码捕获 div 当 div 非常宽或相对于屏幕偏移时

var div = $("#div")[0];
var rect = div.getBoundingClientRect();

var canvas = document.createElement("canvas");
canvas.width = rect.width;
canvas.height = rect.height;

var ctx = canvas.getContext("2d");
ctx.translate(-rect.left,-rect.top);

html2canvas(div, {
    canvas:canvas,
    height:rect.height,
    width:rect.width,
    onrendered: function(canvas) {
        var image = canvas.toDataURL("image/png");
        var pHtml = "<img src="+image+" />";
        $("#parent").append(pHtml);
    }
});

10 2022 10 2022

This question is quite old, but if anyone looking for a clear solution to implement then here it is.这个问题已经很老了,但是如果有人正在寻找一个明确的解决方案来实施,那么就在这里。 This is using Pure JS with html2canvas and FileSaver这是使用带有html2canvasFileSaver纯 JS

I have tested and it works fine.我已经测试过,效果很好。

Capture everything inside a div.捕获 div 中的所有内容。

Step 1第1步

Include the scripts in your footer.在页脚中包含脚本。 jQuery is not needed, These two are fine. jQuery不需要,这两个都可以。 If you already have these two in your file, watch out for the correct version.如果您的文件中已有这两个文件,请注意正确的版本。 I know it's a little thing, but it is important.我知道这是一件小事,但它很重要。

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.0/FileSaver.min.js"></script>

Step 2第2步

Basic div.基本分区The style attribute is optional. style属性是可选的。 I am using it here to make it look presentable.我在这里使用它是为了让它看起来像样。

<div id="savethegirl" style="background-color:coral;color:white;padding:10px;width:200px;">
    I am a Pretty girl 👩
</div>

<button onclick="myfunc()">Save the girl</button>

It should look like this它应该看起来像这样

在此处输入图像描述

Step 3步骤 3

Include this script包括这个脚本

function myfunc(){
    // if you are using a different 'id' in the div, make sure you replace it here.
    var element = document.getElementById("savethegirl");
    html2canvas(element).then(function(canvas) {
        canvas.toBlob(function(blob) {
            window.saveAs(blob, "Heres the Girl.png");
        });
    });
};

Step 4第四步

Click the button and it should save the file.单击按钮,它应该保存文件。

Resources资源

CDN from: https://cdnjs.com/ This is from Carlos Delgado's article ( https://ourcodeworld.com/articles/read/415/how-to-create-a-screenshot-of-your-website-with-javascript-using-html2canvas ). CDN 来自: https://cdnjs.com/这是来自 Carlos Delgado 的文章( https://ourcodeworld.com/articles/read/415/how-to-create-a-screenshot-of-your-website-with- javascript-using-html2canvas )。 I simplified it我简化了

If this answer is useful.如果这个答案有用。
Hit that up arrow It will help others to find it.点击那个向上箭头它会帮助其他人找到它。

I don't know if the answer will be late, but I have used this form.不知道会不会迟到,但是我用过这个表格。

JS: JS:

function getPDF()  {
       html2canvas(document.getElementById("toPDF"),{
        onrendered:function(canvas){
 
        var img=canvas.toDataURL("image/png");
        var doc = new jsPDF('l', 'cm'); 
        doc.addImage(img,'PNG',2,2); 
        doc.save('reporte.pdf'); 
       }
    }); 
}

HTML: HTML:

<div id="toPDF"> 
    #your content...
</div>

<button  id="getPDF" type="button" class="btn btn-info" onclick="getPDF()">
    Download PDF
</button>

It can be easily done using html2canvas, try out the following,使用 html2canvas 可以轻松完成,请尝试以下操作,

try adding the div inside a html modal and call the model id using a jquery function.尝试在 html 模式中添加 div 并使用 jquery 函数调用模型 ID。 In the function you can specify the size (height, width) of the image to be displayed.在该函数中,您可以指定要显示的图像的大小(高度、宽度)。 Using modal is an easy way to capture a html div into an image in a button onclick.使用 modal 是一种在按钮 onclick 中将 html div 捕获到图像中的简单方法。

for example have a look at the code sample,例如看看代码示例,

` `

        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">


            <div class="modal-body">
                <p>Some text in the modal.</p>

` `

paste the div, which you want to be displayed, inside the model.将要显示的 div 粘贴到模型中。 Hope it will help.希望它会有所帮助。

window.open didn't work for me... just a blank page rendered... but I was able to make the png appear on the page by replacing the src attribute of a pre-existing img element created as the target. window.open对我不起作用......只是渲染了一个空白页面......但我能够通过替换作为目标创建的预先存在的img元素的src属性使 png 出现在页面上。

 $("#btn_screenshot").click(function(){ element_to_png("container", "testhtmltocanvasimg"); }); function element_to_png(srcElementID, targetIMGid){ console.log("element_to_png called for element id " + srcElementID); html2canvas($("#"+srcElementID)[0]).then( function (canvas) { var myImage = canvas.toDataURL("image/png"); $("#"+targetIMGid).attr("src", myImage); console.log("html2canvas completed. png rendered to " + targetIMGid); }); }
 <div id="testhtmltocanvasdiv" class="mt-3"> <img src="" id="testhtmltocanvasimg"> </div>

I can then right-click on the rendered png and "save as".然后我可以右键单击渲染的 png 并“另存为”。 May be just as easy to use the "snipping tool" to capture the element, but html2canvas is an certainly an interesting bit of code!使用“截图工具”来捕获元素可能同样容易,但是 html2canvas 肯定是一段有趣的代码!

You can get the screenshot of a division and save it easily just using the below snippet.您可以使用以下代码段获取分区的屏幕截图轻松保存 Here I'm used the entire body, you can choose the specific image/div elements just by putting the id/class names.这里我使用了整个 body,你可以通过输入 id/class 名称来选择特定的图像/div 元素。

 html2canvas(document.getElementsByClassName("image-div")[0], {
  useCORS: true,
}).then(function (canvas) {
  var imageURL = canvas.toDataURL("image/png");
  let a = document.createElement("a");
  a.href = imageURL;
  a.download = imageURL;
  a.click();
});

You should try this (test, works at least in Firefox):你应该试试这个(测试,至少在 Firefox 中有效):

html2canvas(document.body,{
   onrendered:function(canvas){
      document.body.appendChild(canvas);
   }
});

Im running these lines of code to get the full browser screen (only the visible screen, not the hole site):我运行这些代码行以获得完整的浏览器屏幕(只有可见屏幕,而不是孔站点):

var w=window, d=document, e=d.documentElement, g=d.getElementsByTagName('body')[0];
var y=w.innerHeight||e.clientHeight||g.clientHeight;

html2canvas(document.body,{
   height:y,
   onrendered:function(canvas){
      var img = canvas.toDataURL();
   }
});

More explanations & options here: http://html2canvas.hertzen.com/#/documentation.html更多解释和选项在这里: http : //html2canvas.hertzen.com/#/documentation.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM