vue实现管道流动
Vue 实现管道流动效果
在 Vue 中实现管道流动效果可以通过 CSS 动画和动态数据绑定完成。以下是几种常见方法:
使用 CSS 动画和 SVG
通过 SVG 路径动画模拟流体在管道中的运动:
<template>
<svg width="400" height="200">
<path
id="pipe"
d="M50,100 Q200,50 350,100"
stroke="#3498db"
stroke-width="20"
fill="none"
/>
<circle
cx="0"
cy="0"
r="10"
fill="#e74c3c"
:style="{
transform: `translate(${position.x}px, ${position.y}px)`,
transition: 'transform 0.1s linear'
}"
/>
</svg>
</template>
<script>
export default {
data() {
return {
position: { x: 50, y: 100 },
pathLength: 0
}
},
mounted() {
const path = document.getElementById('pipe');
this.pathLength = path.getTotalLength();
setInterval(() => {
const point = path.getPointAtLength(this.position.x % this.pathLength);
this.position = { x: point.x, y: point.y };
this.position.x += 2;
}, 50);
}
}
</script>
使用 CSS 渐变动画
通过背景渐变模拟流动效果:
<template>
<div class="pipe">
<div class="liquid"></div>
</div>
</template>
<style>
.pipe {
width: 300px;
height: 40px;
background: #ddd;
border-radius: 20px;
overflow: hidden;
position: relative;
}
.liquid {
width: 100%;
height: 100%;
background: linear-gradient(90deg,
transparent 0%,
#3498db 20%,
#3498db 80%,
transparent 100%
);
animation: flow 2s linear infinite;
}
@keyframes flow {
0% { transform: translateX(-100%); }
100% { transform: translateX(100%); }
}
</style>
使用 Canvas 实现
更复杂的流体模拟可以使用 Canvas:

<template>
<canvas ref="canvas" width="400" height="200"></canvas>
</template>
<script>
export default {
mounted() {
const canvas = this.$refs.canvas;
const ctx = canvas.getContext('2d');
let position = 0;
function drawPipe() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制管道
ctx.beginPath();
ctx.moveTo(50, 100);
ctx.quadraticCurveTo(200, 50, 350, 100);
ctx.lineWidth = 20;
ctx.strokeStyle = '#ddd';
ctx.stroke();
// 绘制流动液体
ctx.beginPath();
ctx.moveTo(position, 100);
ctx.quadraticCurveTo(position + 150, 50, position + 300, 100);
ctx.lineWidth = 10;
ctx.strokeStyle = '#3498db';
ctx.stroke();
position = (position + 1) % 100;
requestAnimationFrame(drawPipe);
}
drawPipe();
}
}
</script>
使用第三方库
对于更专业的流体模拟,可以考虑使用物理引擎库:
-
安装 Matter.js:

npm install matter-js -
实现示例:
<template> <div ref="scene"></div> </template>
export default { mounted() { const { Engine, Render, Bodies, Composite } = Matter;
const engine = Engine.create();
const render = Render.create({
element: this.$refs.scene,
engine: engine,
options: {
width: 400,
height: 200,
wireframes: false
}
});
// 创建管道和流体粒子
const pipe = Bodies.rectangle(200, 100, 300, 20, {
isStatic: true,
chamfer: { radius: 10 }
});
const particles = Array.from({ length: 20 }, (_, i) =>
Bodies.circle(50 + i * 15, 80, 5, {
restitution: 0.3,
friction: 0.001
})
);
Composite.add(engine.world, [pipe, ...particles]);
Engine.run(engine);
Render.run(render);
} }
```这些方法可以根据实际需求选择,CSS 方案适合简单效果,Canvas 和物理引擎适合更复杂的流体模拟。






