Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

The H5 page is summarized using html5-canvas


May 30, 2021 Article blog



The H5 page is summarized using html5-canvas

The function of the html5canvas plug-in is to copy the contents of the dom node into a dynamically created < canvas >, and the canvas object makes it easy to turn the contents of the canvas into pictures.

Github direct: html2canvas

How to use it
html2canvas(domNode, options).then(function(canvas){
    var img = document.createElement('img');
    img.src = canvas.toDataURL();
    // 成功将原生domNode转成img
});

Used on the H5 page

<script src="js/html2canvas.min.js"></script>
// var domNode = document.getElementById('xxId');
html2canvas(domNode, {
    width: Math.floor(domNode.clientWidth),
    height: Math.floor(domNode.clientHeight),
    scale: 2
}).then(function(canvas) {
    //console.log(canvas);
    //document.body.appendChild(canvas);
    var img = document.createElement('img');
    img.src = canvas.toDataURL();
    img.setAttribute('id', 'xxxImage');
    // 将img展示到页面上
    // prependChild(img, domNode);
});

Parameter interpretation:

  • width: specifies the style width of the dynamically created canvas, which is recommended to match the actual width of domNode;
  • height: specifies the style height of the dynamically created canvas, which is recommended to match the actual height of domNode;
  • scale : Zoom ratio, the author suggests setting to 2, which is equivalent to expanding the drawing width/height of the canvas canvas to 2 times the width/height of the styler. The resulting picture is clearer and avoids blurring.

Precautions

1, the measured IOS on the call html5canvas no response, Android model normal.

2, domNode in all pictures using <img > label introduction, do not use the background-image method. Otherwise, the picture may not be clear.

3, cross-domain picture does not show the problem, add configuration parameters . . . allowTaint:true, useCORS: true .

4, png picture transparency loss problem, add configuration parameters . . . backgroundColor: "transparent" .

5, do not use <br/> label for text wrapping, use < p> or < div > label rewrite.

6, the problem of generating part of the picture, may be that when the html5canvas method is called, the domNode node itself has not been rendered (for example, the domNode node itself is participating in a zoom dynamic), plus an appropriate delay can be.

7, the bottom of the generated picture has the problem of leaving white, this is domNode in the bottom of the picture itself has left white, set the picture style display:block/inline-block can be.