Loading

使用js的html2canvas截图div并下载

html

<div id="save">
    <img src="" alt="">
</div>
<div id="canvas" class="rank_data_box">
    <div style="color: red;">截图这里</div>
    <!-- 数据空 -->
</div>

引用js

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>

js示例

function getScreenShot(){
    html2canvas(document.querySelector("#canvas")).then(canvas => {
        var t = canvas.toDataURL().replace("data:image/png;base64,", "");
        const linkSource = 'data:image/png;base64,'+t;
        //生成图片,并展示
        $("#canvas").hide();
        $("#save img").attr('src',linkSource)
        //还可以直接下载图片
        downloadBase64File('image/png',t,'image');
    });
}
$(document).ready(function(){
    getScreenShot();
})
function downloadBase64File(contentType, base64Data, fileName) {
    const linkSource = `data:${contentType};base64,${base64Data}`;
    const downloadLink = document.createElement("a");
    downloadLink.href = linkSource;
    downloadLink.download = fileName;
    console.log(downloadLink)
    downloadLink.click();
}

官网

https://html2canvas.hertzen.com/

posted @ 2023-03-14 13:21  王召波  阅读(197)  评论(0编辑  收藏  举报