<template>
<div class="home" :style="{ '--main-color': mainColor }">
<h1>{{ greeting }}</h1>
<button @click="changeColor">改变颜色</button>
<div ref="imageTofile" class="dashboard-container home-box">
<div id="map"></div>
</div>
</div>
</template>
<script>
import html2canvas from 'html2canvas'
import * as L from 'leaflet';
import 'leaflet/dist/leaflet.css';
var map = null;
export default {
name: "HomeView",
components: {},
created() {
},
data() {
return {
mainColor: 'orange',
greeting: '你好Vue中的CSS变量示例!',
}
},
mounted() {
this.initMap();
},
methods: {
initMap() {
map = L.map('map', {
layers: [L.tileLayer(
"http://t0.tianditu.gov.cn/img_w/wmts?" +
"SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles" +
"&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=aa9562c28c1ed05634ec493cd395730e"
),],
center: [32.80000472399998, 118.985428473],
zoom: 17,
zoomControl: false,
attributionControl: false,
maxNativeZoom: 17,
});
},
toImage() {
// 第一个参数是需要生成截图的元素,第二个是自己需要配置的参数,宽高等
html2canvas(this.$refs.imageTofile, {
backgroundColor: null,
useCORS: true // 如果截图的内容里有图片,可能会有跨域的情况,加上这个参数,解决文件跨域问题
}).then((canvas) => {
const url = canvas.toDataURL('image/png')
this.htmlUrl = url
console.log('生成的url', this.htmlUrl)
const imgFile = this.base64ImgtoFile(this.htmlUrl);
console.log("imgFile", imgFile);
})
},
base64ImgtoFile(dataurl, filename = 'file') {
let arr = dataurl.split(',')
let mime = arr[0].match(/:(.*?);/)[1]
let suffix = mime.split('/')[1]
let bstr = atob(arr[1])
let n = bstr.length
let u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new File([u8arr], `${filename}.${suffix}`, {
type: mime
})
},
changeColor() {
this.toImage()
this.mainColor = 'red';
this.greeting = '颜色已更改!';
}
},
};
</script>
<style>
h1 {
color: var(--main-color)
}
button {
margin-top: 10px;
padding: 8px 16px;
background-color: var(--main-color);
color: #fff;
border: none;
cursor: pointer;
}
#map {
width: 700px;
height: 700px;
}
</style>
vue 截图转base64转图片文件file
最新推荐文章于 2024-08-22 11:40:32 发布