Search code examples
javascriptscreenshothtml2canvas

html2canvas is not working in Safari browser: Taking Screenshot


I just want to take a screenshot of any HTML element ( "container" div in my case ). it works fine in Chrome and Firefox browsers but not in Safari.

Following is how I am doing it:

<!doctype HTML>
<HTML>
<head>
    <script type="text/javascript" src="assets/HTML_canvas/html2canvas.js"></script>
</head>
<body>
<h1>Take screenshot of webpage with html2canvas</h1>
<div class="container" id='container' >
    <div style="background-color: blue; height: 50px; width: 50px;">DIV 1</div>
    <div style="background-color: red; height: 50px; width: 50px;">DIV 2</div>
    <div style="background-color: green; height: 50px; width: 50px;">DIV 3</div>
</div>

<input type='button' id='but_screenshot' value='Take screenshot' onclick='screenshot();'><br/>

<!-- Script -->
<script type='text/javascript'>
    function screenshot(){
        html2canvas(document.getElementById('container')).then(function(canvas) {
            document.body.appendChild(canvas);
        });
    }
</script>

</body>
</html>

it shows the following error in the Safari browser: enter image description here

and here is the specific part of code of html2canvas.js (it is by-default file I have just used). enter image description here


Solution

  • we just have to enable the CORS in safari-mac browser. So, we'll do it by modifying our function screenshot() as follows:

    function screenshot(){
        html2canvas(document.getElementById('id-screenshot'),{
            allowTaint: true,
            useCORS : true,
        }).then(function(canvas) {
            console.log("canvas: " + canvas);
            document.getElementById('test-s').appendChild(canvas);
        });
    }