h5写长按保存图片到手机相册

h5写长按保存图片到手机相册

话不多说直接上代码
首先引入html2canvas
import html2canvas from ‘html2canvas’

 
//模板部分
"contents"> "./img/psb.jpg" alt="" class="imgs">

然后是js部分

  var imgs= document.getElementsByClassName('imgs')[0]
           console.log(imgs)
            
                let w = imgs.offsetWidth;
                let h = imgs.offsetHeight;
               
                //要将 canvas 的宽高设置成容器宽高的 2 倍
                let canvas = document.createElement("canvas");
                canvas.width = w;
                canvas.height = h;
                canvas.style.width = w + "px";
                canvas.style.height = h*2 + "px";
                let context = canvas.getContext("2d");
                //然后将画布缩放,将图像放大两倍画到画布上
                context.scale(2, 2);
              console.log(imgs.offsetWidth)

                html2canvas(imgs,{canvas: canvas, useCORS: true}).then(function(canvas){

                    var dataUrl = canvas.toDataURL();
                    var imgs= document.getElementsByClassName('imgs')[0]

                      imgs.scale(1, 1);
                      // imgs.style.height = imgs.offsetHeight/2;
                        imgs.src = dataUrl;
                        console.log(imgs.offsetWidth)
                        
                     
                });

注:方法要在mounted里面调用,否则会获取不到内容

你可能感兴趣的:(h5写长按保存图片到手机相册)