<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"> <title>element查看大图添加下载按钮</title> </head> <body> <div id="app"> <div class="demo-image__preview" @click="checkImage"> <el-image style="width: 100px; height: 100px" :src="url" :preview-src-list="srcList"> </el-image> </div> </div> <!-- <i class="el-icon-download" onclick="installImage()"></i> --> </body> <!-- import Vue before Element --> <script src="https://unpkg.com/vue/dist/vue.js"></script> <!-- import JavaScript --> <script src="https://unpkg.com/element-ui/lib/index.js"></script> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> let vueEle = null; window.installImage = function() { alert(111) console.log('下载') let srcUrl = document.querySelector('.el-image-viewer__img').src; vueEle.downloadIamge(srcUrl, '图片名字'); } vueEle = new Vue({ el: '#app', data: function() { return { url: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg', srcList: [ 'https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg', 'https://fuss10.elemecdn.com/1/8e/aeffeb4de74e2fde4bd74fc7b4486jpeg.jpeg' ] } }, methods: { checkImage() { //这个事件要绑定el-image父级盒子上 console.log('点击事件'); let a = document.querySelector('.el-image-viewer__actions__inner'); $(a).append(`<i class="el-icon-download" onclick="installImage()"></i>`) }, downloadIamge(imgsrc, name) { //下载图片地址和图片名 let image = new Image(); // 解决跨域 Canvas 污染问题 image.setAttribute("crossOrigin", "anonymous"); image.onload = function() { let canvas = document.createElement("canvas"); canvas.width = image.width; canvas.height = image.height; let context = canvas.getContext("2d"); context.drawImage(image, 0, 0, image.width, image.height); let url = canvas.toDataURL("image/png"); //得到图片的base64编码数据 let a = document.createElement("a"); // 生成一个a元素 let event = new MouseEvent("click"); // 创建一个单击事件 a.download = name || "photo"; // 设置图片名称 a.href = url; // 将生成的URL设置为a.href属性 a.dispatchEvent(event); // 触发a的单击事件 }; image.src = imgsrc; } } }) </script> </html>