Home  >  Article  >  Web Front-end  >  How to convert html into image format using js

How to convert html into image format using js

coldplay.xixi
coldplay.xixiOriginal
2021-02-20 10:54:286516browse

JS method to convert html into image format: first use html2canvas to convert html into canvas; then use the canvas object method [toDataURL()] to convert canvas into image.

How to convert html into image format using js

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, DELL G3 computer. This method is suitable for all brands of computers.

JS method of converting html into image format:

1. First, use html2canvas to convert html into canvas

html2canvas($('#content'),{
    onrendered: function(canvas) {
        document.body.appendChild(canvas);
    }
})

2. Use canvas object Method: toDataURL() converts canvas into image

function convertCanvasToImage(canvas) {
    var image = new Image();
    image.src = canvas.toDataURL("image/png");
    return image;
}

The obtained data format is: data:image/png;base64...

The complete code is as follows:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="jquery.min.js"></script>
    <script src="html2canvas.js"></script>
</head>
<body>
    <div id="content" style="width:150px;height:150px;border:1px solid blue;">
        <span>Hello World!</span>
        <br>
        <span><h2>Are you hear me?</h2></span>
    </div>
    <button id="btnSave">save</button>
<script>
$(function(){
    $(&#39;#btnSave&#39;).click(function(event) {
        html2canvas($(&#39;#content&#39;),{
            onrendered: function(canvas) {
                document.body.appendChild(canvas);
                convertCanvasToImage(canvas);
            }
        })
    });
    function convertCanvasToImage(canvas) {
        var image = new Image();
        image.src = canvas.toDataURL("image/png");
        document.body.appendChild(image);
        return image;
    }
})
</script>
</body>
</html>

Related free learning recommendations: javascript video tutorial

The above is the detailed content of How to convert html into image format using js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn