vue2中类似于兵旗推演的移动效果的页面代码
时间: 2024-04-09 15:29:23 浏览: 7
下面是一个使用Vue.js和CSS动画实现类似兵旗推演移动效果的页面代码示例:
```html
<template>
<div class="container">
<div class="board">
<div
class="piece"
v-for="(piece, index) in pieces"
:key="index"
:style="{ top: piece.y * 50 + 'px', left: piece.x * 50 + 'px' }"
@click="movePiece(index)"
></div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
pieces: [
{ x: 0, y: 0 },
{ x: 1, y: 0 },
{ x: 2, y: 0 },
{ x: 0, y: 1 },
{ x: 1, y: 1 },
{ x: 2, y: 1 }
]
};
},
methods: {
movePiece(index) {
const piece = this.pieces[index];
const newPosition = { x: piece.x + 1, y: piece.y + 1 };
this.animateMove(piece, newPosition);
},
animateMove(piece, newPosition) {
const startTop = piece.y * 50;
const startLeft = piece.x * 50;
const endTop = newPosition.y * 50;
const endLeft = newPosition.x * 50;
const distanceTop = endTop - startTop;
const distanceLeft = endLeft - startLeft;
const keyframes = [
{ top: startTop + 'px', left: startLeft + 'px' },
{ top: endTop + 'px', left: endLeft + 'px' }
];
const options = {
duration: 1000,
easing: 'linear'
};
const pieceElement = document.getElementsByClassName('piece')[piece.x + piece.y * 3];
pieceElement.animate(keyframes, options);
}
}
};
</script>
<style>
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.board {
position: relative;
width: 150px;
height: 150px;
border: 1px solid #000;
}
.piece {
position: absolute;
width: 50px;
height: 50px;
background-color: red;
}
</style>
```
在这个示例中,我们使用了一个名为`pieces`的数组来表示棋盘上的兵旗。每个兵旗对象都有`x`和`y`属性,表示其在棋盘上的位置。
当点击一个兵旗时,会调用`movePiece`方法来移动该兵旗。在`animateMove`方法中,我们计算起始位置和目标位置之间的距离,并使用CSS动画来实现平滑移动效果。通过调用`animate`方法,我们传入关键帧和选项来定义动画的持续时间和缓动函数。
请注意,这只是一个简单的示例,你可以根据实际需求自定义棋盘和兵旗的样式,并根据具体情况调整动画效果。