How HTML 2 canvas converts HTML code into pictures

Time:2019-3-21

Conversion code to picture usage

Html2canvas, a well-known open source library for screenshots of web pages from browsers, is easy to use and powerful.

Using HTML 2 canvas

The use of html2 canvas is simple enough to simply pass in a DOM element and get canvas by callback:

How HTML 2 canvas converts HTML code into pictures

In practical use, there are two points of attention:

1. HTML 2 canvas generates canvas image content by parsing the actual style of the element, so it has requirements for the actual layout and visual display of the element. If you want a full screenshot, it’s best to separate the elements from the document stream (for example, position: absolute)

2. The default canvas image is very blurred on the retina device, which can be solved by processing it into two-fold images:

var w = $("#code").width();  
Var H = $("# code"). height (); // Set the width of canvas to twice the width of the container  
var canvas = document.createElement("canvas");  
    canvas.width = w * 2;  
    canvas.height = h * 2;  
    canvas.style.width = w + "px";  
    canvas.style.height = h + "px";  
Var context = canvas. getContext ("2d"); and // then zoom the canvas and double the image onto the canvas  
    context.scale(2,2);  
    html2canvas(document.querySelector("#code"), {          
canvas: canvas,         
 onrendered: function(canvas) 
{                ...        
  }    
});

A Practical Case of Using HTML 2 canvas

1. HTML code structure
 

<section class="share_popup" id="html2canvas">  
<p> The use of html2 canvas is simple enough to simply pass in a DOM element and get canvas through callbacks</p>  
<p><img src="1.jpg"></p>  
<p> The use of html2 canvas is simple enough to simply pass in a DOM element and get canvas through callbacks</p>  
 </section>

2. JS code structure


var str = $('#html2canvas');  
//console.log(str);  
html2canvas([str.get(0)], {  
    onrendered: function (canvas) {  
        var image = canvas.toDataURL("image/png");  
        var pHtml = "<img src="+image+" />";  
        $('#html2canvas').html(pHtml);  
    }  
});  

summary

Above is the introduction of HTML 2 canvas to you. I hope it will be helpful to you. If you have any questions, please leave a message for me. The editor will reply to you in time. Thank you very much for your support to developpaer.