vue3 vite实现对某个标签截屏方式
更新时间:2026年07月02日 09:19:30 作者:jjw_zyfx
这段代码实现了截图功能,点击截图后会自动展示结果,非常适合网站和应用用场景,简化操作流程提升用户体验
全部代码如下
<template>
<div id="yourElementId">
<canvas ref="canvas"></canvas>
<button @click="captureScreen">截屏</button>
</div>
<div style="margin-top: 10px">
<img :src="shot_image" alt="">
</div>
</template>
<script setup>
import { ref } from 'vue';
import html2canvas from 'html2canvas';
const canvas = ref(null);
const shot_image = ref("");
// 1. 定义自定义事件,声明事件名和参数类型(传递base64字符串)
const emit = defineEmits(['imageCaptured']);
function captureScreen() {
const element = document.getElementById('yourElementId');
html2canvas(element).then(canvas => {
shot_image.value = canvas.toDataURL('image/png');
console.log('截图生成成功:', shot_image.value);
// 2. 截图生成后,触发自定义事件,传递base64图片数据
// emit('imageCaptured', shot_image.value); // 如果需要传递给父组件可以这样实现
}).catch(error => {
console.error('截图生成失败:', error);
alert('截图失败,请重试!');
});
}
</script>
<style scoped>
#yourElementId {
width: 100%;
height: 500px;
background-color: pink;
position: relative;
}
button {
margin: 10px;
padding: 8px 16px;
cursor: pointer;
}
</style>
截图前效果

点击截图后的效果

即点击截图后会在下方自动将截图的结果展示出来
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。


最新评论