duanraa1984
2018-06-12 06:00 阅读 59

如何从页面保存多个画布

I have a page in which i have multiple canvases. I have a function that allows me to save each canvas one at a time. This function looks like this:

<button onclick="download()">Download</button>
<script>
    function download() {
        var link = document.createElement('a');
        link.download = "pass.jpg";
        link.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
        link.click();
    }
</script>

This is ok if a have maximum 10 canvases, but if my page has 200 canvases to download it would be a problem to click 200 buttons to download them all. I tried to make a function that would save all the canvases from the page at once but it's not quite working. Here is my code:

<button onclick="download()">Download</button>
<script>
    function download() {
        var images = document.getElementById("canvas");
        var srcList = [];
        var i = 0;

        setInterval(function() {
            if (images.length > i) {
                srcList.push(images[i].src);
                var link = document.createElement("a");
                link.id = i;
                link.download = "pass.jpg";
                link.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
                link.click();
                i++;
            }
        }, 1500);
    }
</script>

How can i modify this code to get the result i want?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dtvp3625 dtvp3625 2018-06-12 06:38

    Change getElementById to getElementsByTagName to get all canvas elements in array. And add clearInterval to stop the loop as mentiond by @PHPglue

    var images = document.getElementsByTagName("canvas");
    var srcList = [];
    var i = 0;
    
    var timer = setInterval(function(){
        if(images.length > i){
            var link = document.createElement("a");
            srcList.push(images[i].src);
            link.id = i;
            link.download = "pass.jpg";
            link.href = images[i].toDataURL("image/png").replace("image/png", "image/octet-stream");
            link.click();
            i++;
        } else {
            clearInterval(timer);
        }
    },1500);
    
    点赞 评论 复制链接分享

相关推荐