本来写这个特效 我打算用css实现的,结果是一波三折,我太难了,最终没能用css实现,转战了canvas来实现。来吧先看效果图
当然这个图的波浪高度、频率、位置、速度都是可调的,请根据自己的需求调整,如果你讲波浪什么的调大一下 还有有摆动的效果哦。
以下是完整代码
import React, { useEffect, useRef } from 'react';
import classNames from 'classnames';
const WaveAnimation = () => {
const canvasRef = useRef<HTMLCanvasElement | null>(null);
useEffect(() => {
const canvas = canvasRef.current;
if (canvas) {
const ctx = canvas.getContext('2d');
console.log('ctx', ctx);
if (ctx) {
const amplitude = 60;
const frequency = 0.006;
let phase = 0;
const centerY = canvas.height / 2;
const startX = -10;
const speed = 0.2;
const lineColor = 'rgba(255, 255, 255, 0.1)';
const animate = () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.moveTo(startX, centerY);
for (let x = startX; x < canvas.width; x++) {
const y = centerY + amplitude * Math.sin(frequency * x + phase);
ctx.lineTo(x, y);
}
ctx.strokeStyle = lineColor;
ctx.lineWidth = 10;
ctx.stroke();
phase -= speed;
requestAnimationFrame(animate);
};
animate();
}
}
}, []);
return (
<div className="wave-animation">
<canvas ref={canvasRef} width="3000" height="300"></canvas>
</div>
);
};
export default WaveAnimation;
如果你想看vue的写法,请移步这里