效果图
<template>
<div>
<canvas id="my-canvas" width="500" height="300"></canvas>
<div>
<span id="clear" class="d-block">重置</span>
<span id="sure" class="d-block sure">确认</span>
</div>
</div>
</template>
<script>
export default {
data() {
return {};
},
mounted() {
const canvas = document.getElementById("my-canvas");
const clear = document.getElementById("clear");
const sure = document.getElementById("sure");
const ctx = canvas.getContext("2d");
ctx.lineWidth = 5;
canvas.addEventListener("mouseenter", () => {
canvas.addEventListener("mousedown", (e) => {
ctx.beginPath();
ctx.moveTo(e.offsetX, e.offsetY);
canvas.addEventListener("mousemove", draw);
});
canvas.addEventListener("mouseup", (e) => {
canvas.removeEventListener("mousemove", draw);
});
});
function draw(e) {
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
}
clear.addEventListener("click", () => {
canvas.removeEventListener("mousemove", draw);
ctx.clearRect(0, 0, canvas.width, canvas.height);
});
sure.addEventListener("click", clickFn);
// 点击截图函数
function clickFn() {
// 将canvas转换成base64的url
let url = canvas.toDataURL("image/png");
const Img = new Image();
// 把Canvas 转化为图片
Img.src = url;
// 将base64转换为文件对象
let arr = url.split(",");
let mime = arr[0].match(/:(.*?);/)[1]; // 此处得到的为文件类型
let bstr = atob(arr[1]); // 此处将base64解码
let n = bstr.length;
let u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
// 通过以下方式将以上变量生成文件对象,三个参数分别为文件内容、文件名、文件类型
let file = new File([u8arr], "filename", { type: mime });
// 将文件对象通过a标签下载
let aDom = document.createElement("a"); // 创建一个 a 标签
aDom.download = file.name; // 设置文件名
let href = URL.createObjectURL(file); // 将file对象转成 UTF-16 字符串
aDom.href = href; // 放入href
document.body.appendChild(aDom); // 将a标签插入 body
aDom.click(); // 触发 a 标签的点击
document.body.removeChild(aDom); // 移除刚才插入的 a 标签
URL.revokeObjectURL(href); // 释放刚才生成的 UTF-16 字符串
}
},
};
</script>
<style lang="scss" scoped>
#my-canvas {
margin: 200 auto 0;
box-shadow: 0px 0px 5px #ccc;
border-radius: 8px;
background-color: #fff;
}
.d-block {
cursor: pointer;
display: inline-block;
width: 250px;
height: 40px;
line-height: 40px;
text-align: center;
background-color: rgb(16, 61, 46);
color: #fff;
}
.sure {
background-color: rgb(151, 130, 83);
}
</style>
代码来自:https://juejin.cn/post/7171484788602175495
网友评论