vue图片实现旋转
使用 CSS transform 实现图片旋转
在 Vue 中可以通过 CSS 的 transform 属性实现图片旋转效果。创建一个数据属性控制旋转角度,通过绑定样式动态更新。
<template>
<div>
<img
:src="imageSrc"
:style="{ transform: `rotate(${rotationAngle}deg)` }"
/>
<button @click="rotateImage">旋转图片</button>
</div>
</template>
<script>
export default {
data() {
return {
imageSrc: 'path/to/your/image.jpg',
rotationAngle: 0
}
},
methods: {
rotateImage() {
this.rotationAngle += 90
}
}
}
</script>
使用 CSS 动画实现连续旋转
如果需要实现连续旋转动画效果,可以定义 CSS 关键帧动画并通过类名控制。
<template>
<div>
<img
:src="imageSrc"
:class="{ 'rotate-animation': isRotating }"
/>
<button @click="toggleRotation">
{{ isRotating ? '停止旋转' : '开始旋转' }}
</button>
</div>
</template>
<script>
export default {
data() {
return {
imageSrc: 'path/to/your/image.jpg',
isRotating: false
}
},
methods: {
toggleRotation() {
this.isRotating = !this.isRotating
}
}
}
</script>
<style>
.rotate-animation {
animation: rotation 2s linear infinite;
}
@keyframes rotation {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
</style>
使用第三方动画库
Vue 可以结合第三方动画库如 GSAP 或 anime.js 实现更复杂的旋转效果。以 GSAP 为例:
<template>
<div>
<img ref="rotatableImage" :src="imageSrc" />
<button @click="animateRotation">高级旋转</button>
</div>
</template>
<script>
import gsap from 'gsap'
export default {
data() {
return {
imageSrc: 'path/to/your/image.jpg'
}
},
methods: {
animateRotation() {
gsap.to(this.$refs.rotatableImage, {
rotation: 360,
duration: 1,
ease: "elastic.out(1, 0.3)",
repeat: 1,
yoyo: true
})
}
}
}
</script>
响应式旋转控制
通过滑块控件实时调整旋转角度,实现交互式旋转效果。
<template>
<div>
<img
:src="imageSrc"
:style="{ transform: `rotate(${currentRotation}deg)` }"
/>
<input
type="range"
min="0"
max="360"
v-model="currentRotation"
/>
<span>当前角度: {{ currentRotation }}°</span>
</div>
</template>
<script>
export default {
data() {
return {
imageSrc: 'path/to/your/image.jpg',
currentRotation: 0
}
}
}
</script>
每种方法适用于不同场景,CSS transform 适合简单旋转,CSS 动画适合持续旋转,GSAP 适合复杂动画效果,滑块控制适合需要精确调整的场景。







