Home > Web Front-end > JS Tutorial > body text

How to convert html into image format using js

coldplay.xixi
Release: 2023-01-03 09:23:59
Original
6544 people have browsed it

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);
    }
})
Copy after login

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;
}
Copy after login

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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!