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 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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测