使用transform生成一个火车在倾斜轨道上跑 点击按钮背景图不动 标记点动的动画 使用vue2怎么写
时间: 2024-05-03 19:18:55 浏览: 16
首先,您需要安装 `vue2` 和 `vue2-animate` 插件。
在您的Vue组件中,您可以使用 `transform` 属性来控制元素的位置和旋转。为了使标记点动起来,您可以使用 `vue2-animate` 来实现动画效果。
以下是一个示例代码:
```html
<template>
<div class="train-track">
<div class="train" :style="{ transform: 'rotate(' + trainRotation + 'deg)' }"></div>
<div v-for="(point, index) in points" :key="index" class="point" :style="{ left: point.left + '%', top: point.top + '%', transform: 'rotate(' + point.rotation + 'deg)' }"></div>
<button @click="startTrain">Start Train</button>
</div>
</template>
<script>
import { animate } from 'vue2-animate'
export default {
data() {
return {
trainRotation: 0,
points: [
{ left: 10, top: 20, rotation: 0 },
{ left: 20, top: 30, rotation: 45 },
{ left: 30, top: 40, rotation: 90 },
{ left: 40, top: 50, rotation: 135 },
{ left: 50, top: 60, rotation: 180 },
{ left: 60, top: 70, rotation: 225 },
{ left: 70, top: 80, rotation: 270 },
{ left: 80, top: 90, rotation: 315 },
],
trainSpeed: 10,
trainInterval: null,
}
},
methods: {
startTrain() {
if (this.trainInterval) {
clearInterval(this.trainInterval)
}
this.trainRotation = 0
this.trainInterval = setInterval(() => {
this.trainRotation += this.trainSpeed
if (this.trainRotation >= 360) {
this.trainRotation = 0
}
}, 100)
this.animatePoints()
},
animatePoints() {
this.points.forEach((point, index) => {
animate(
`.${index}.point`,
{
opacity: [0, 1],
translateX: [0, `${point.left}%`],
translateY: [0, `${point.top}%`],
},
{
duration: 2000,
delay: 1000 * index,
}
)
})
},
},
}
</script>
<style scoped>
.train-track {
position: relative;
width: 100vw;
height: 100vh;
background-image: url('/path/to/train-track.jpg');
background-size: cover;
background-position: center;
}
.train {
position: absolute;
top: 50%;
left: 50%;
width: 20%;
height: 10%;
background-image: url('/path/to/train.png');
background-size: contain;
background-position: center;
background-repeat: no-repeat;
transform-origin: center center;
}
.point {
position: absolute;
width: 5%;
height: 5%;
background-image: url('/path/to/point.png');
background-size: contain;
background-position: center;
background-repeat: no-repeat;
transform-origin: center center;
}
</style>
```
在这个代码中,我们首先在 `data` 中定义了火车的旋转角度 `trainRotation`,标记点的位置和旋转角度 `points`,火车的速度 `trainSpeed` 和动画间隔 `trainInterval`。
在 `startTrain` 方法中,我们使用 `setInterval` 来定期更新火车的旋转角度,并调用 `animatePoints` 方法来为每个标记点添加动画效果。
在 `animatePoints` 方法中,我们使用 `vue2-animate` 的 `animate` 方法来实现动画效果。我们为每个标记点指定了不同的延迟时间,以创建一个顺序动画效果。
最后,我们在模板中使用 `v-for` 循环渲染每个标记点,并使用 `:style` 属性来设置它们的位置和旋转角度。我们还为火车和标记点分别设置了样式,并在按钮上绑定了 `startTrain` 方法。