vue实现小球教学
Vue实现小球动画的基础方法
使用Vue实现小球动画可以通过结合CSS过渡和JavaScript动画库。以下是一个基础实现示例:
创建Vue组件模板部分
<template>
<div class="ball-container">
<div
class="ball"
:style="{
left: position.x + 'px',
top: position.y + 'px',
backgroundColor: color
}"
@click="moveBall"
></div>
</div>
</template>
添加组件脚本逻辑
<script>
export default {
data() {
return {
position: { x: 0, y: 0 },
color: '#ff0000',
speed: 5
}
},
methods: {
moveBall() {
this.position.x += Math.random() * 30 - 15
this.position.y += Math.random() * 30 - 15
this.color = `#${Math.floor(Math.random()*16777215).toString(16)}`
}
}
}
</script>
样式部分设计
<style scoped>
.ball-container {
position: relative;
width: 100%;
height: 300px;
border: 1px dashed #ccc;
}
.ball {
position: absolute;
width: 50px;
height: 50px;
border-radius: 50%;
cursor: pointer;
transition: all 0.3s ease;
}
</style>
使用GSAP实现高级动画
对于更复杂的动画效果,可以集成GSAP动画库:
安装GSAP依赖
npm install gsap
在Vue组件中使用GSAP
import { gsap } from 'gsap'
export default {
methods: {
bounceBall() {
gsap.to(this.$refs.ball, {
duration: 1,
x: Math.random() * 200 - 100,
y: Math.random() * 200 - 100,
ease: "bounce.out"
})
}
}
}
实现物理效果的小球碰撞
添加物理引擎实现真实碰撞效果:
安装matter-js物理引擎
npm install matter-js
创建物理世界和小球
import Matter from 'matter-js'
export default {
mounted() {
const engine = Matter.Engine.create()
const render = Matter.Render.create({
element: this.$refs.world,
engine: engine,
options: {
width: 800,
height: 600,
wireframes: false
}
})
const ball = Matter.Bodies.circle(400, 200, 30, {
restitution: 0.8
})
Matter.Composite.add(engine.world, [
ball,
Matter.Bodies.rectangle(400, 610, 810, 60, { isStatic: true })
])
Matter.Engine.run(engine)
Matter.Render.run(render)
}
}
响应式小球尺寸控制
使用Vue的计算属性实现响应式尺寸:
添加计算属性
computed: {
ballSize() {
return window.innerWidth < 768 ? 30 : 50
}
}
模板中使用动态尺寸
<div
class="ball"
:style="{
width: ballSize + 'px',
height: ballSize + 'px'
}"
></div>
多小球交互系统
实现多个小球的创建和交互:
数据结构和方法
data() {
return {
balls: [],
colors: ['#FF5252', '#FF4081', '#E040FB', '#7C4DFF', '#536DFE']
}
},
methods: {
addBall() {
this.balls.push({
id: Date.now(),
x: Math.random() * 500,
y: Math.random() * 300,
color: this.colors[Math.floor(Math.random() * this.colors.length)]
})
},
removeBall(id) {
this.balls = this.balls.filter(ball => ball.id !== id)
}
}
渲染多个小球
<div
v-for="ball in balls"
:key="ball.id"
class="ball"
:style="{
left: ball.x + 'px',
top: ball.y + 'px',
backgroundColor: ball.color
}"
@click="removeBall(ball.id)"
></div>






