1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- export const drawCircle = (domId: string, type: number, rateNum: number) => {
- const colorObj = type === 1 ?{
- start: '#279FFE',
- end: '#43C8FE',
- bg: '#D9EEFF',
- textColor: '#259CFE',
- } : {
- start: '#24BD90',
- end: '#7CE3C5',
- bg: '#E8F6F2',
- textColor: '#24BD90',
- }
- // 获取canvas元素和上下文
- const canvas: any = document.getElementById(domId);
- const ctx = canvas.getContext('2d');
- // 设置百分比(0-100)
- const percentage = rateNum || 0;
- // 圆环的设置
- const radius = 30; // 圆环半径
- const lineWidth = 8; // 圆环的宽度
- // 圆心坐标
- const centerX = canvas.width / 2;
- const centerY = canvas.height / 2;
- // 创建渐变色
- function createGradient() {
- const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
- gradient.addColorStop(0, colorObj.start); // 渐变开始颜色
- gradient.addColorStop(1, colorObj.end); // 渐变结束颜色
- return gradient;
- }
- // 绘制背景圆环
- function drawBackgroundCircle() {
- ctx.beginPath();
- ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
- ctx.lineWidth = lineWidth;
- ctx.strokeStyle = colorObj.bg; // 背景圆环的颜色
- ctx.lineJoin = 'round'; // 设置圆角效果
- ctx.stroke();
- }
- // 绘制进度圆环
- function drawProgressCircle() {
- const startAngle = -0.5 * Math.PI; // 起始角度,从顶部开始
- const endAngle = (percentage / 100) * 2 * Math.PI - 0.5 * Math.PI; // 结束角度,按照百分比计算
- ctx.beginPath();
- ctx.arc(centerX, centerY, radius, startAngle, endAngle);
- ctx.lineWidth = lineWidth;
- ctx.strokeStyle = createGradient(); // 进度圆环使用渐变色
- ctx.lineJoin = 'round'; // 设置圆角效果
- ctx.stroke();
- }
- // 绘制百分比文本
- function drawText() {
- ctx.font = '18px DIN';
- ctx.fillStyle = colorObj.textColor;
- ctx.textAlign = 'center';
- ctx.textBaseline = 'middle';
- ctx.fillText(percentage + '%', centerX, centerY-6); // 绘制百分比文本
- }
- // 清除文本区域
- function clearTextArea() {
- const textWidth = ctx.measureText(percentage + '%').width; // 获取文本宽度
- const padding = 10; // 给文本区域留一些边距
- // 清除文本区域的矩形区域
- ctx.clearRect(centerX - textWidth / 2 - padding, centerY - 24 - padding, textWidth + padding * 2, 48);
- }
- clearTextArea();
- drawBackgroundCircle(); // 绘制背景圆环
- drawProgressCircle(); // 绘制进度圆环
- drawText();
-
- }
|