欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

html2canvas将html转化成图片

程序员文章站 2022-07-14 19:20:34
...
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>html2canvas</title>
    <script src="http://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>

    <style>
     .box{
         padding: 10px;
         background: grey;
         width: 200px;
     }
     </style>
</head>
<body>
<h1>html内容</h1>
<div id="htmlcanvas" class="box" >
    <h1>h1</h1>
    <h2>h2</h2>
    <h3>h3</h3>
    <strong>strong</strong>
</div>
<h1>canvas内容</h1>
<div id="canvas"></div>

<h1>image内容</h1>
<img id="image" src=""/>

<script>
    html2canvas(document.querySelector("#htmlcanvas")).then(canvas => {

        document.getElementById("canvas").appendChild(canvas);

        // 转成图片
        canvasToImage(canvas);
    });

    // Converts canvas to an image
    function canvasToImage(canvas) {
        document.getElementById("image").setAttribute('src',canvas.toDataURL("image/png"))
    }
</script>
</body>
</html>

x效果图
html2canvas将html转化成图片

相关标签: javascript html/css