iT邦幫忙

0

pchome買了東西,把當前UI畫面截圖儲起來,怎麼做?(用html2canvas轉成canvas,再下載

  • 分享至 

  • xImage
  •  

想要跟pchome一樣可以截圖,意外的google到這個元件,真好用

開始

用html2canvas轉成canvas,再下載

載入js,js會把div裡的東西,轉換成canvas

<head>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
</head>

準備容器,把要截圖的內容,包在裡面(等等轉成canvas)

    <div id="capture" style="padding: 10px; background: #f5da55">
        <h4 style="color: #000; ">Hello world!</h4>        
    </div>

將canvas下載成jpg

    <script>
        function block_capture() {
            html2canvas(document.querySelector("#capture")).then(function (canvas) {              
                a = document.createElement('a');//add canvas
                a.href = canvas.toDataURL("image/jpeg", 0.92).replace("image/jpeg", "image/octet-stream");//toDataURL將canvas轉成base64
                //下載成png     toDataURL("image/png")
                //下載成jpg     toDataURL("image/jpeg")
                a.download = 'image.jpg';
                a.click();
            });
        }
    </script>

全文

<!DOCTYPE html>
<html lang="zh-tw">

<head>
    <meta charset=" UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
    <title>JavaScript canvas</title>
    <style>
        button{
            margin: 5px;
        }
    </style>
</head>

<body>
    <div id="capture" style="padding: 10px; background: #f5da55">
        <h4 style="color: #000; ">Hello world!</h4>
        <table><tr><td>3333</td></tr></table>
    </div>
    <button onclick="block_capture()">Click</button>
    <script>
        function block_capture() {
            html2canvas(document.querySelector("#capture")).then(function (canvas) {
                a = document.createElement('a');
                a.href = canvas.toDataURL("image/jpeg", 0.92).replace("image/jpeg", "image/octet-stream");
                a.download = 'image.jpg';
                a.click();
            });
        }
    </script>
</body>

</html>

ref
https://mnya.tw/cc/word/1573.html


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言