目录
前言
1、将当前窗口截图,并将数据存储下来
2、定义将base64转png的方法
3、完整代码
总结
前言
记录来源于需求
1、将当前窗口截图,并将数据存储下来
export default {
data() {return {image: '' // 存储数据}
}mounted() {setTimeout(() => {// 拿到当前dom里 你需要截取的位置的idconst dom = document.querySelector("#cesium canvas");if (dom) {// 将选择的dom元素转换为PNG格式的DataURL字符串,打印出来是base64数据this.image = dom.toDataURL("image/png");}},500)}
}
2、定义将base64转png的方法
methods: {base64ImgtoFile(dataurl, filename = "file") {return new Promise((resolve, reject) => {const image = new Image();image.src = dataurl;image.onload = () => {const canvas = document.createElement("canvas");canvas.width = image.width;canvas.height = image.height;const context = canvas.getContext("2d");context.drawImage(image, 0, 0);canvas.toBlob((blob) => {const file = new File([blob], `${filename}.png`, {type: "image/png"});resolve(file);}, "image/png");};image.onerror = (error) => reject(error);});},async convertBase64ToPNG(dataurl, fileName) {try {const file = await this.base64ImgtoFile(dataurl, fileName);// 使用转换后的文件进行后续操作return file;} catch (error) {console.error(error);}},
}
3、完整代码
<template><el-button @click="handleSaveMap">提交</el-button>
</template><script>
export default {data() {return {image: "" // 存储数据};},mounted() {setTimeout(() => {// 拿到当前dom里 你需要截取的位置的idconst dom = document.querySelector("#cesium canvas");if (dom) {// 将选择的dom元素转换为PNG格式的DataURL字符串,打印出来是base64数据this.image = dom.toDataURL("image/png");}}, 500);},methods: {base64ImgtoFile(dataurl, filename = "file") {return new Promise((resolve, reject) => {const image = new Image();image.src = dataurl;image.onload = () => {const canvas = document.createElement("canvas");canvas.width = image.width;canvas.height = image.height;const context = canvas.getContext("2d");context.drawImage(image, 0, 0);canvas.toBlob((blob) => {const file = new File([blob], `${filename}.png`, {type: "image/png"});resolve(file);}, "image/png");};image.onerror = (error) => reject(error);});},async convertBase64ToPNG(dataurl, fileName) {try {const file = await this.base64ImgtoFile(dataurl, fileName);// 使用转换后的文件进行后续操作return file;} catch (error) {console.error(error);}},// 存储数据到服务端async generateImages(image) {const file = new FileReader(); // 创建对象file.readAsDataURL(image); // 读取文件const res = await uploadApi.uploadImage(image); // 对接上传接口const { object, msg, success } = res.data;if (success) {this.areaPicture = object.key;} else this.$message.error(msg);},// 保存数据async handleSaveMap() {const loading = this.$loading({lock: true,text: "保存中,请稍后...",spinner: "el-icon-loading",background: "rgba(0, 0, 0, 0.7)"});// 截取当前窗口数据await this.screenshotView();// 转换当前base64图片数据为pnglet image = await this.convertBase64ToPNG(this.image, this.mapName);// 存储到服务端if (image) {await this.generateImages(image);console.log(this.areaPicture, "this.areaPicture");}loading.close();}}
};
</script>
总结
对你有帮助的话 点点赞吧~