前端实现图片旋转vue
使用 CSS transform 实现图片旋转
在 Vue 中可以通过绑定样式实现图片旋转效果。定义一个数据属性存储旋转角度,通过点击事件修改角度值。

<template>
<div>
<img
:style="{ transform: `rotate(${rotation}deg)` }"
src="your-image.jpg"
@click="rotateImage"
/>
</div>
</template>
<script>
export default {
data() {
return {
rotation: 0
}
},
methods: {
rotateImage() {
this.rotation += 90
}
}
}
</script>
使用 CSS 动画实现连续旋转
添加 CSS 动画关键帧实现无限旋转效果,通过类名切换控制动画启停。

<template>
<div>
<img
:class="{ 'rotate-animation': isRotating }"
src="your-image.jpg"
@click="toggleRotation"
/>
</div>
</template>
<script>
export default {
data() {
return {
isRotating: false
}
},
methods: {
toggleRotation() {
this.isRotating = !this.isRotating
}
}
}
</script>
<style>
.rotate-animation {
animation: rotation 2s infinite linear;
}
@keyframes rotation {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
</style>
使用第三方库实现复杂旋转
安装 vue-draggable-resizable 等库可实现带拖拽功能的旋转控制。
npm install vue-draggable-resizable
<template>
<div>
<vue-draggable-resizable
:rotatable="true"
:w="200"
:h="200"
>
<img src="your-image.jpg" />
</vue-draggable-resizable>
</div>
</template>
<script>
import VueDraggableResizable from 'vue-draggable-resizable'
export default {
components: {
VueDraggableResizable
}
}
</script>
实现手势旋转功能
通过监听 touch 事件计算旋转角度,适合移动端场景。
<template>
<div
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
>
<img
:style="{ transform: `rotate(${rotation}deg)` }"
src="your-image.jpg"
/>
</div>
</template>
<script>
export default {
data() {
return {
rotation: 0,
startAngle: 0,
isRotating: false
}
},
methods: {
calculateAngle(x, y) {
return Math.atan2(y, x) * 180 / Math.PI
},
handleTouchStart(e) {
const rect = e.target.getBoundingClientRect()
const centerX = rect.left + rect.width / 2
const centerY = rect.top + rect.height / 2
const touchX = e.touches[0].clientX
const touchY = e.touches[0].clientY
this.startAngle = this.calculateAngle(touchX - centerX, touchY - centerY) - this.rotation
this.isRotating = true
},
handleTouchMove(e) {
if (!this.isRotating) return
const rect = e.target.getBoundingClientRect()
const centerX = rect.left + rect.width / 2
const centerY = rect.top + rect.height / 2
const touchX = e.touches[0].clientX
const touchY = e.touches[0].clientY
const angle = this.calculateAngle(touchX - centerX, touchY - centerY)
this.rotation = angle - this.startAngle
},
handleTouchEnd() {
this.isRotating = false
}
}
}
</script>






