rsp
rsp

Reputation: 13

image get downloaded multiple times

I am trying to download some area of the page as an image. for that, I have used html2canvas.js. that thing is working perfectly but my problem is when i click on download link image is get downloaded multiple times and it won't stop unless i close the page. i don't know where I am wrong and why this is happening. I am posting my code here please help me out.

function to download an image.

 <script>
    function genImageFile() {
                html2canvas($('.pvtRendererArea')[0]).then(function (canvas) {
                    if (navigator.userAgent.indexOf("MSIE ") > 0 ||
                        navigator.userAgent.match(/Trident.*rv\:11\./)) {
                        var blob = canvas.msToBlob();
                        window.navigator.msSaveBlob(blob, 'Test file.png');
                    } else {
                        $('#mytest').attr('href', canvas.toDataURL("image/png"));
                        $('#mytest').attr('download', $('#title').text() + '.png');
                        $('#mytest')[0].click();
                    }
                }
                )
            };
        </script>

Html from where i call that function:

<a onclick="genImageFile()" id="mytest" value="Image View" class="button"><br> PNG </a>

Upvotes: 0

Views: 618

Answers (1)

nishant
nishant

Reputation: 2606

You can use the following code

<script>
function genImageFile() {
            html2canvas($('.pvtRendererArea')[0]).then(function (canvas) {
                if (navigator.userAgent.indexOf("MSIE ") > 0 ||
                    navigator.userAgent.match(/Trident.*rv\:11\./)) {
                    var blob = canvas.msToBlob();
                    window.navigator.msSaveBlob(blob, 'Test file.png');
                } else {
                    var link = document.createElement('a');
                    link.download = $('#title').text() + '.png';
                    link.href = canvas.toDataURL("image/png");
                    link.click();
                }
            }
            )
        };
    </script>

Upvotes: 1

Related Questions