const draw = (canvas: HTMLCanvasElement, percentage: number, offset: number, color: string[]) => {
const cWidth = canvas.width;
const cHeight = canvas.height;
let context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
let gradient = context.createLinearGradient(0, 0, 0, cHeight);
gradient.addColorStop(1, color[0]);
gradient.addColorStop(0, color[1]);
// 设置渐变为填充样式
context.fillStyle = gradient;
context.beginPath();
context.moveTo(0, cHeight * percentage);
context.lineTo(0, cHeight);
context.lineTo(cWidth, cHeight);
context.lineTo(cWidth, cHeight * percentage);
const num = 3; // 正弦个数
const A = 5; // 振幅
for (let x1 = cWidth; x1 >= 0; x1 -= 0.01) {
let y = A * Math.sin(x1 * (Math.PI / (cWidth / (num * 2))) + offset) + cHeight * percentage;
context.lineTo(x1, y);
}
context.closePath();
context.fill();
};
export default (
elId: string,
per: number = 0,
color = ['rgba(80,115,249,0.3)', 'rgba(39,193,128,0.3)']
) => {
const percentage = 1 - per;
let timer: any;
onMounted(() => {
const container = document.getElementById(elId);
const width = container.offsetWidth;
const height = container.offsetHeight;
const canvas = document.createElement('canvas');
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
canvas.style.borderRadius = '50%';
container.appendChild(canvas);
let offset = 0;
timer = setInterval(() => {
if (offset - 1 < Number.MIN_SAFE_INTEGER) {
offset = 0;
}
draw(canvas, percentage, (offset -= 0.15) * Math.PI, color);
}, 100);
});
onUnmounted(() => {
timer && clearInterval(timer);
});
return {};
};
使用
useCanvasWave('cw-out-car-img-cur', 0.4676, ['rgba(154,57,171,0.4)', 'rgba(78,110,241,0.4)']);
效果