vue实现液态玻璃
Vue实现液态玻璃效果
液态玻璃效果是一种视觉上类似液体流动或玻璃折射的动画,通常结合CSS滤镜、SVG或Canvas实现。以下是基于Vue的实现方法:
使用CSS滤镜和动画
通过Vue动态绑定CSS样式,结合filter和animation实现基础效果:
<template>
<div
class="liquid-glass"
:style="{
'--blur': blur + 'px',
'--hue': hue + 'deg'
}"
@mousemove="handleMove"
></div>
</template>
<script>
export default {
data() {
return {
blur: 5,
hue: 180
}
},
methods: {
handleMove(e) {
this.blur = 5 + (e.clientX / window.innerWidth) * 10;
this.hue = (e.clientY / window.innerHeight) * 360;
}
}
}
</script>
<style>
.liquid-glass {
width: 300px;
height: 300px;
background: linear-gradient(45deg, #ff00cc, #3333ff);
border-radius: 20px;
filter: blur(var(--blur)) hue-rotate(var(--hue));
transition: filter 0.3s ease;
}
</style>
结合Canvas实现动态流体
通过Vue管理Canvas绘制逻辑,实现更复杂的流体效果:
<template>
<canvas ref="canvas" width="600" height="400"></canvas>
</template>
<script>
export default {
mounted() {
const canvas = this.$refs.canvas;
const ctx = canvas.getContext('2d');
let time = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 创建液态波纹效果
for(let i = 0; i < 10; i++) {
ctx.beginPath();
ctx.arc(
300 + Math.sin(time + i) * 100,
200 + Math.cos(time + i * 2) * 100,
50 + Math.sin(time) * 20,
0,
Math.PI * 2
);
ctx.fillStyle = `hsla(${200 + i * 10}, 80%, 60%, 0.4)`;
ctx.filter = 'blur(10px)';
ctx.fill();
}
time += 0.02;
requestAnimationFrame(animate);
}
animate();
}
}
</script>
使用第三方库(如Three.js)
对于更高级的3D液态玻璃效果,可以结合Vue和WebGL库:
<template>
<div ref="container"></div>
</template>
<script>
import * as THREE from 'three';
export default {
mounted() {
const container = this.$refs.container;
// 初始化Three.js场景
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, container.clientWidth / container.clientHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(container.clientWidth, container.clientHeight);
container.appendChild(renderer.domElement);
// 创建液态材质
const geometry = new THREE.SphereGeometry(2, 64, 64);
const material = new THREE.MeshPhysicalMaterial({
color: 0x1188ff,
transmission: 0.9,
roughness: 0.1,
clearcoat: 1,
ior: 1.5
});
const sphere = new THREE.Mesh(geometry, material);
scene.add(sphere);
camera.position.z = 5;
function animate() {
requestAnimationFrame(animate);
sphere.rotation.x += 0.005;
sphere.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
}
}
</script>
响应式调整
在Vue中监听窗口变化并动态调整效果:
export default {
// ...
mounted() {
window.addEventListener('resize', this.handleResize);
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
},
methods: {
handleResize() {
// 更新Canvas或Three.js渲染器尺寸
}
}
}
关键实现要点
- CSS方案适合简单效果,性能开销小
- Canvas方案可实现自定义流体动画,需要手动管理绘制逻辑
- WebGL方案适合3D效果,但学习曲线较陡
- 通过Vue的响应式特性动态控制参数(如颜色、模糊度等)
- 鼠标交互可通过事件监听实现效果变化
以上方法可根据项目需求选择或组合使用,CSS方案适合大多数基础场景,而Canvas/WebGL方案适合需要复杂视觉效果的项目。

