关于pc端和移动端长长按图保存到本地的问题

时间:2022-12-11 18:48:45

1.pc端:

<canvas id=‘canvas‘ width="500" height="500"></canvas>
        <!-- <img src="http://gss0.baidu.com/-4o3dSag_xI4khGko9WTAnF6hhy/lvpics/h=800/sign=b49dc48f8718367ab28972dd1e728b68/9922720e0cf3d7ca7f0736d0f31fbe096a63a9a6.jpg" > -->
            <button id="save">保存</button>
            <script type="text/javascript">
                        
                    window.onload = function(){
                        var canvas = document.getElementById(‘canvas‘)
                        var ctx = canvas.getContext(‘2d‘)
             
                        // 内存中先加载,然后当内存加载完毕时,再把内存中的数据填充到我们的 dom元素中,这样能够快速的去
                        // 反应,比如网易的图片
                        var img = new Image();
                        img.setAttribute("crossOrigin",‘anonymous‘);//需要放在图片赋值前,否则部分浏览器会报错
                        img.onload = function(){
                            // alert(‘加载完毕‘)
                            
                            // 将图片画到canvas上面上去!
                            ctx.drawImage(img,593,327,500,500,100,100,300,300);
             
             
                        }
                        img.src = "http://gss0.baidu.com/-4o3dSag_xI4khGko9WTAnF6hhy/lvpics/h=800/sign=b49dc48f8718367ab28972dd1e728b68/9922720e0cf3d7ca7f0736d0f31fbe096a63a9a6.jpg";
                        // img.src = "http://rc.rry.info/app/index.php?i=1&c=entry&m=ewei_shopv2&do=mobile&r=order.pay.chanPayQrcode&url=https://qr.alipay.com/bax062248bb2tkmy1ubv2071";
             
                    }    
                    document.getElementById("save").onclick = function (){
                        console.log(‘canvas‘,canvas)
                        downLoad(saveAsJPG(canvas));
                    }
                    
                    // 保存成png格式的图片
                    function saveAsPNG(canvas) {
                        return canvas.toDataURL("image/png");
                    }
                    // 保存成jpg格式的图片
                    function saveAsJPG(canvas) {
                        return canvas.toDataURL("image/jpeg");
                    }
                    function downLoad(url){
                        var oA = document.createElement("a");
                        oA.download = ‘img‘;// 设置下载的文件名,默认是‘下载‘
                        oA.href = url;
                        document.body.appendChild(oA);
                        oA.click();
                        oA.remove(); // 下载之后把创建的元素删除
                    }
             
                </script>

 

2.移动端:此方法针对多组图片,多个图片可以添加相同的class然后js根据class的长度来进行操作。其中主要用到plus.downloader.createDownload(url, options, completedCB);

    • url: String ) 必选 要下载文件资源地址
      要下载文件的url地址,仅支持网络资源地址,支持http或https协议。 允许创建多个相同url地址的下载任务。 注意:如果url地址中包含中文或空格等,需要进行urlencode转换。
    • options: DownloadOptions ) 可选 下载任务的参数
      可通过此参数设置下载任务属性,如保存文件路径、下载优先级等。
    • completedCB: DownloadCompletedCallback ) 可选 下载任务完成回调函数
      当下载任务下载完成时触发,成功或失败都会触发
<img src="H5canvas鼠标经过的地方星星连接/xkbg.png"  id="image">
        <!-- 弹框的html-->
        <div id="picture" class="mui-popover mui-popover-action mui-popover-bottom" style="z-index: 99999999">
            <ul class="mui-table-view">
                <li class="mui-table-view-cell">
                    <a href="javascript:;" id="saveImg">保存图片</a>
                </li>
            </ul>
            <ul class="mui-table-view">
                <li class="mui-table-view-cell">
                    <a href="#picture"><b>取消</b></a>
                </li>
            </ul>
        </div>
        <script type="text/javascript">
             mui.init( { gestureConfig:{
                tap: true, //默认为true
                doubletap: true, //默认为false
                longtap: true, //默认为false
                swipe: true, //默认为true
                drag: true, //默认为true
                hold:true,//默认为false,不监听
                release:false//默认为false,不监听
            }});
            document.getElementById(‘image‘).onclick = function(){
                //给需要长按保存图片的img标签设置 class=‘saveImg‘
                 var divs = document.getElementsByClassName(‘saveImg‘);
                    for(var i = 0;i<divs.length;i  ){
                      divs[i].addEventListener(‘longtap‘, function () {
                        //开启弹框
                          mui(‘#picture‘).popover(‘toggle‘);
                          console.log(this.src)
                          var imgurl = this.src;
                          document.getElementById(‘saveImg‘).addEventListener(‘tap‘, function () {
                            var imgDtask = plus.downloader.createDownload(imgurl,{method:‘GET‘}, function (d,status) {
                                    if(status == 200){
                                        plus.gallery.save(d.filename, function () {//保存到相册
                                            plus.io.resolveLocalFileSystemURL(d.filename, function (enpty) {
                                            // 关闭弹框
                                                mui(‘#picture‘).popover(‘toggle‘);
                                                mui.toast(‘保存成功‘)
                                            });
                 
                                        })
                                    }else{
                                        mui.toast(‘保存失败‘)
                                    }
                              });
                            imgDtask.start();
                          });
                   
                      })
                    }
            }
        </script>

3.移动端单张图片:注意plus.downloader.createDownload(url, options, completedCB)中的url是图片在服务器端的路径比如:https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1335795923,3245280170&fm=15&gp=0.jpg这种格式,而不是文件资源!

    <script src="js/mui.min.js"></script>
    <link href="css/mui.min.css" rel="stylesheet"/>
    <script src="js/jquery-2.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript" charset="utf-8">
          mui.init();
    </script>
    <style type="text/css">
        #imageList{
            display: flex;
            
        }
        .cs{
            width: 0;
            height: 0;
        }
        .saveImg1{
            width: 100%;
            height: 100%;
            visibility: hidden;
        }
    </style>
</head>
<body>
    <!-- <img id="image" style="width: 300px;height: 300px;" src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1571203612306&di=42932c7868bcb8054af73d53d0b24ff6&imgtype=0&src=http://hbimg.b0.upaiyun.com/28ea2e5cf17173f84ef74064e95627cc3ba75fe627e71-hKNgS4_fw658"  > -->
    <div class="imageList">
        <div id="">
            <canvas id=‘canvas‘ width="300" height="300"></canvas>
        </div>
        <div class="cs">
            <img class="saveImg1" style="width: 200px;height: 200px;" src="https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1335795923,3245280170&fm=15&gp=0.jpg"  >
        </div>
        <div id="image">
            保存
        </div>
    </div>
            <!-- 弹框的html-->
            <div id="picture" class="mui-popover mui-popover-action mui-popover-bottom" style="z-index: 99999999">
                <ul class="mui-table-view">
                    <li class="mui-table-view-cell">
                        <a href="javascript:;" id="saveImg">保存图片</a>
                    </li>
                </ul>
                <ul class="mui-table-view">
                    <li class="mui-table-view-cell">
                        <a href="#picture"><b>取消</b></a>
                    </li>
                </ul>
            </div>
    <script type="text/javascript">
        mui.init( { gestureConfig:{
            tap: true, //默认为true
            doubletap: true, //默认为false
            longtap: true, //默认为false
            swipe: true, //默认为true
            drag: true, //默认为true
            hold:true,//默认为false,不监听
            release:false//默认为false,不监听
        }});
        window.onload = function(){
            var canvas = document.getElementById(‘canvas‘)
            var ctx = canvas.getContext(‘2d‘)
                     
            // 内存中先加载,然后当内存加载完毕时,再把内存中的数据填充到我们的 dom元素中,这样能够快速的去
            // 反应,比如网易的图片
            var img = new Image();
            img.setAttribute("crossOrigin",‘anonymous‘);//需要放在图片赋值前,否则部分浏览器会报错
            img.onload = function(){
                // 将图片画到canvas上面上去!
                ctx.drawImage(img,593,327,500,500,100,100,300,300);
                     
                     
            }
            img.src = "http://gss0.baidu.com/-4o3dSag_xI4khGko9WTAnF6hhy/lvpics/h=800/sign=b49dc48f8718367ab28972dd1e728b68/9922720e0cf3d7ca7f0736d0f31fbe096a63a9a6.jpg";
            // img.src = "http://rc.rry.info/app/index.php?i=1&c=entry&m=ewei_shopv2&do=mobile&r=order.pay.chanPayQrcode&url=https://qr.alipay.com/bax062248bb2tkmy1ubv2071";
                     $(‘.saveImg1‘).attr(‘src‘,img.src)
                     
                     
                     
        }    
        
        // document.getElementById(‘image‘).addEventListener(‘tap‘,function(){
            console.log(‘点击图片了‘)
            //给需要长按保存图片的img标签设置 class=‘saveImg‘
             var divs = $(‘.saveImg1‘);
              $(‘#canvas‘)[0].addEventListener(‘longtap‘, function () {
            //开启弹框
              mui(‘#picture‘).popover(‘toggle‘);
              var imgurl = divs[0].src;
              document.getElementById(‘saveImg‘).addEventListener(‘tap‘, function () {
                var imgDtask = plus.downloader.createDownload(imgurl,{method:‘GET‘}, function (d,status) {
                    console.log(typeof(imgurl))
                    console.log(imgurl)
                    console.log(JSON.stringify(d))
                    console.log(JSON.stringify(status))
                    if(status == 200){
                        plus.gallery.save(d.filename, function () {//保存到相册
                            plus.io.resolveLocalFileSystemURL(d.filename, function (enpty) {
                            // 关闭弹框
                                mui(‘#picture‘).popover(‘toggle‘);
                                mui.toast(‘保存成功‘)
                            });
 
                        })
                    }else{
                        mui.toast(‘保存失败‘)
                    }
              });
            imgDtask.start();
          });
       
          })
</script>

 4.自己用canvas画图并下载

<div id="app"></div>
    <canvas id="canvas" width="400" height="400"></canvas>
    <div>
        <button id="save">保存</button>
    </div>
</body>
<script>
    var arr = [
        {locations:[[0,0],[200,200],[0,400]],color:"red"},
        {locations:[[0,0],[400,0],[200,200]],color:"orange"},
        {locations:[[0,400],[100,300],[200,400]],color:"yellow"},
        {locations:[[100,300],[200,200],[300,300],[200,400]],color:"green"},
        {locations:[[300,100],[200,200],[300,300]],color:"blue"},
        {locations:[[300,100],[400,0],[400,200],[300,300]],color:"indigo"},
        {locations:[[200,400],[400,400],[400,200]],color:"purple"}
    ];
    var oCanvas = document.getElementById("canvas");
    var ctx = oCanvas.getContext("2d");
    for(let i=0;i<arr.length;i  ){
        draw(arr[i],ctx);
    }

    function draw(item,ctx){
        ctx.beginPath();
        ctx.moveTo(item.locations[0][0],item.locations[0][1]);
        for(let i = 0;i<item.locations.length;i  ){
            let x = item.locations[i][0];
            let y = item.locations[i][1];
            ctx.lineTo(x,y);
            console.log(1234567)
        }
        ctx.closePath();

        ctx.fillStyle = item.color;
        ctx.fill();

        ctx.strokeStyle = "#000";
        ctx.lineWidth = 2;
        ctx.stroke();
    }
    var imgId = document.getElementById("imgId");
    document.getElementById("save").onclick = function (){
        console.log(‘canvas‘,canvas)
        downLoad(saveAsPNG(canvas));
    }

    // 保存成png格式的图片
    function saveAsPNG(canvas) {
        return canvas.toDataURL("image/png");
    }

    // 保存成jpg格式的图片
    function saveAsJPG(canvas) {
        return canvas.toDataURL("image/jpeg");
    }

    // 保存成bmp格式的图片  目前浏览器支持性不好
    function saveAsBMP(canvas) {
        return canvas.toDataURL("image/bmp");
    }

    /**
     * @author web得胜
     * @param {String} url 需要下载的文件地址
     * */
    function downLoad(url){
        var oA = document.createElement("a");
        oA.download = ‘img‘;// 设置下载的文件名,默认是‘下载‘
        oA.href = url;
        document.body.appendChild(oA);
        console.log(oA)
        oA.click();
        oA.remove(); // 下载之后把创建的元素删除
    }
</script>