其他分享
首页 > 其他分享> > 使用a链接实现点击下载网络图片

使用a链接实现点击下载网络图片

作者:互联网

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
       
    </style>
</head>
<body>
    <img src="http://192.168.0.71:3000/a1.jpg" alt="" class="img">
    
    <button onclick="downImg()">点击下载图片</button>

    <!-- <a href="http://192.168.0.71:3000/a1.jpg" download>使用a链接下载图片</a> -->

    <script>
        function downImg(){
            let a = document.createElement('a');
            let img = document.querySelector('.img');
            img.crossOrigin = 'anonymous';
            img.onload = function(){
                let data = getBase64Img(img);
                console.log(data);
                a.setAttribute('href', data);
                a.setAttribute('download', "");
                let event = document.createEvent('MouseEvents');
                event.initMouseEvent('click', true, true, window,0,0,0,0,0,false,false,true,false,0,null);
                a.dispatchEvent(event)
            };
        }

        function getBase64Img(img){
            let canvas = document.createElement("canvas");
            canvas.width = img.width;
            canvas.height = img.height;
            let ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0, img.width, img.height);
            let dataUrl = canvas.toDataURL("image/png");
            return dataUrl;
        }
    </script>
</body>
</html>

 

标签:canvas,false,img,height,点击,let,document,链接,下载
来源: https://www.cnblogs.com/xyzcba/p/16602388.html