vue实现取景框
在Vue中实现取景框功能,通常用于图像裁剪、扫描识别等场景。以下是几种常见的实现方式:
基于Canvas的实现
通过Canvas绘制取景框,结合鼠标交互实现动态调整:
<template>
<div class="viewport">
<canvas ref="canvas" @mousedown="startDrag" @mousemove="onDrag" @mouseup="endDrag"></canvas>
<div class="frame" :style="frameStyle"></div>
</div>
</template>
<script>
export default {
data() {
return {
frame: { x: 100, y: 100, width: 200, height: 200 },
isDragging: false
}
},
computed: {
frameStyle() {
return {
left: `${this.frame.x}px`,
top: `${this.frame.y}px`,
width: `${this.frame.width}px`,
height: `${this.frame.height}px`
}
}
},
methods: {
startDrag(e) {
this.isDragging = true
this.dragStart = { x: e.clientX, y: e.clientY }
},
onDrag(e) {
if (!this.isDragging) return
const dx = e.clientX - this.dragStart.x
const dy = e.clientY - this.dragStart.y
this.frame.x += dx
this.frame.y += dy
this.dragStart = { x: e.clientX, y: e.clientY }
},
endDrag() {
this.isDragging = false
}
}
}
</script>
<style>
.viewport {
position: relative;
width: 500px;
height: 500px;
}
.frame {
position: absolute;
border: 2px dashed #fff;
box-shadow: 0 0 0 10000px rgba(0,0,0,0.5);
}
</style>
使用第三方库
对于更复杂的取景框需求,可以使用专门的图像处理库:
安装cropperjs:
npm install cropperjs
Vue组件实现:
<template>
<div>
<img ref="image" src="your-image.jpg" alt="">
</div>
</template>
<script>
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'
export default {
mounted() {
this.cropper = new Cropper(this.$refs.image, {
aspectRatio: 16 / 9,
viewMode: 1,
autoCropArea: 0.8,
guides: true,
center: true,
highlight: false,
cropBoxMovable: true,
cropBoxResizable: true
})
},
beforeDestroy() {
this.cropper.destroy()
}
}
</script>
纯CSS实现
简单的静态取景框可以通过CSS实现:
<template>
<div class="camera-view">
<div class="frame"></div>
</div>
</template>
<style>
.camera-view {
position: relative;
width: 100%;
height: 100vh;
background: rgba(0,0,0,0.7);
}
.frame {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 70%;
height: 50%;
border: 2px solid white;
box-shadow: 0 0 0 100vmax rgba(0,0,0,0.5);
}
</style>
结合WebRTC实现实时取景
对于摄像头实时取景场景:
<template>
<div class="camera-container">
<video ref="video" autoplay playsinline></video>
<div class="overlay-frame"></div>
</div>
</template>
<script>
export default {
mounted() {
navigator.mediaDevices.getUserMedia({ video: true })
.then(stream => {
this.$refs.video.srcObject = stream
})
},
beforeDestroy() {
const stream = this.$refs.video.srcObject
stream.getTracks().forEach(track => track.stop())
}
}
</script>
<style>
.camera-container {
position: relative;
}
.overlay-frame {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 300px;
height: 300px;
border: 2px solid red;
pointer-events: none;
}
</style>
以上方法可根据具体需求选择使用,Canvas方案适合需要自定义交互的场景,第三方库提供更完整的图像处理功能,CSS方案适合简单静态展示,WebRTC方案适用于实时摄像头取景。







