JS download pictures to the local, solve cross-domain problems

Speaking of requirements, click the button to realize the function of downloading pictures to the local. The url returned in the background is the address where Ali oss stores the pictures. At first, only the pictures can be previewed. Later, affected by the same-origin policy, it still cannot be realized, but it is being generated. After the picture is spliced? time=the current timestamp can be achieved

code show as below:

function downloadImage(imgsrc, name) {
    
    //下载图片地址和图片名
        var image = new Image();
        // 解决跨域 Canvas 污染问题,
        image.setAttribute("crossorigin", "anonymous");
        image.onload = function() {
    
    
            var canvas = document.createElement("canvas");
            canvas.width = image.width;
            canvas.height = image.height;
            var context = canvas.getContext("2d");
            context.drawImage(image, 0, 0, image.width, image.height);
            var url = canvas.toDataURL("image/png"); //将图片格式转为base64
            var a = document.createElement("a"); // 生成一个a元素
            var event = new MouseEvent("click"); // 创建一个单击事件
            a.download = name || "myPhoto"; // 设置图片名称
            a.href = url; // 将生成的URL设置为a.href属性
            a.dispatchEvent(event); // 触发a的单击事件
        };
            image.src = imgsrc + '?time=' + Date.now();  //注意,这里是灵魂,否则依旧会产生跨域问题
            
        }

Guess you like

Origin blog.csdn.net/YL971129/article/details/113763575