import React, { useRef, useEffect } from 'react';
export default (props) => {
const { canvasWidth = 160, canvasHeight = 160 } = props
const canvasRef = useRef(null)
useEffect(() => {
const initCanvas = () => {
const {
x0 = canvasWidth / 2,//原点坐标
y0 = canvasHeight / 2,
r = (canvasWidth - (props.lineWidth || 15)) / 2,// 半径
lineWidth = 15, // 环形宽度
strokeStyle = '#eee', //背景环形颜色
LinearGradientColor1 = '#29bdd9', //起始渐变颜色
LinearGradientColor2 = '#276ace', //结束渐变颜色
Percentage,// 进度百分比
} = props
const rad = Math.PI * 2 / 100;
let speed = 0;
let ele = canvasRef.current
let circle = ele.getContext("2d");
//创建背景圆
function drawBg() {
circle.lineWidth = lineWidth;
circle.strokeStyle = strokeStyle;
circle.lineCap = 'round';
circle.beginPath();//开始一个新的路径
circle.arc(x0, y0, r, 0, 2 * Math.PI, false);///用于绘制圆弧context.arc(x坐标,y坐标,半径,起始角度,终止角度,顺时针/逆时针)
circle.stroke();//对当前路径进行描边
}
function drawCircle(n) {
//创建渐变圆环
let g = circle.createLinearGradient(x0, 0, x0 + r * Math.cos(Percentage * (Math.PI * 2)), y0 + r * Math.sin(Percentage * (Math.PI * 2))); //创建渐变对象 渐变开始点和渐变结束点
g.addColorStop(0, LinearGradientColor1); //添加颜色点
g.addColorStop(1, LinearGradientColor2);
circle.lineWidth = lineWidth - 1.5 //设置线条宽度
circle.lineCap = 'round';
circle.strokeStyle = g;
circle.beginPath();//开始一个新的路径
circle.arc(x0, y0, r, -Math.PI / 2, -Math.PI / 2 + n * rad, false);
circle.stroke();//对当前路径进行描边
}
(function drawFrame() {
window.requestAnimationFrame(drawFrame);
circle.clearRect(0, 0, 80, 80);
drawBg();
drawCircle(speed);
if (speed >= Percentage) return;
speed += 1;
}());
}
initCanvas()
}, [canvasWidth, canvasHeight, props])
return (
<canvas ref={canvasRef} width={canvasWidth} height={canvasHeight} style={{ backgroundColor: 'rgba(0,0,0,0)' }}></canvas>
)
}
react hooks + canvas实现动态圆环效果
最新推荐文章于 2024-06-19 09:11:23 发布