0
0

html2canvasでモバイルサイトのスクリーンショットを撮る方法

Posted at

やりたいこと

スマホでモバイルサイトを開いて、Webページ全体のスクリーンショットを撮りたい

やり方

html2canvasライブラリを使いやりました。
ユーザーから見るとスクリーンショットをそのまま撮るように見えますが、裏ではhtmlファイルのDOMツリーやCSSツリーを解釈してcanvasで描画するみたいなことをしました。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML to Canvas</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
</head>
<body>
    <div id="capture" style="width: 100%; height: 2000px; background: lightblue; text-align: center; line-height: 200px;">
        <h1>Hello, World!</h1>
        <h2>長いサイトだよ</h2>
        <h3>高さ2000px</h3>
    </div>
    <button id="download">Download as Image</button>

    <script>
        document.getElementById('download').addEventListener('click', function() {
            html2canvas(document.body).then(function(canvas) {
                // Convert the canvas to a data URL
                var link = document.createElement('a');
                link.href = canvas.toDataURL('image/png');
                link.download = 'capture.png';
                // Trigger the download
                link.click();
            });
        });
    </script>
</body>
</html>

結果はこんな感じです。
スマホ画面ではスクロールしないと一番下の要素が見れないですが、

image.png

ボタンクリックしたらWebページを上からしたまで撮りました。

capture (2).png

全画面で撮りたい場合はbody指定ですが、
html2canvas(document.body)
一部しか撮りたい場合はその要素だけ指定しても大丈夫です!
html2canvas(document.getElementById('capture'))

参考サイト

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0