<template>
<div class="index">
<!-- 用的element-ui需注册 -->
<el-button @click="download()">下载图片</el-button>
</div>
</template>
<script>
export default {
data() {
return {
Img: "https://m1.im5i.com/2022/09/25/UFWId.png", // 图片链接
};
},
methods: {
download() {
var image = new Image();
image.setAttribute("crossOrigin", "anonymous");
var _this = this;
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 = _this.projectName || "photo"; // 设置图片名称
a.href = url; // 将生成的URL设置为a.href属性
a.dispatchEvent(event); // 触发a的单击事件
};
image.src = this.Img;
},
},
};
</script>