Day 23 - 用 canvas 与 requestAnimationFrame 做 进度条

前述

虽然用一般的 css 就可以完成进度条,但为了符合主题,用了 canvas 来完成!

codesendBox

import React, { useState, useRef, useEffect } from "react";

const CanvasCircle = () => {
  const canvasRef = useRef(null);
  const [context, setContext] = useState(null);
  const [centerX, setCenterX] = useState(0);
  const [centerY, setCenterY] = useState(0);
  const [rad, setRad] = useState(0);
  const [speed, setSpeed] = useState(0.1);

  useEffect(() => {
    const canvas = canvasRef.current; // Get canvas elements
    const ctx = canvas.getContext("2d");

    setContext(ctx);
    const CentX = canvas.width / 2; // Canvas central point X-axis coordinates
    const CentY = canvas.height / 2; // Canvas center point y axis coordinates
    const Rad = (Math.PI * 2) / 100;
    setCenterX(CentX);
    setCenterY(CentY);
    setRad(Rad);
  }, [canvasRef]);

  useEffect(() => {
    const drawFrame = () => {
      if (context) {
        context.clearRect(0, 0, 500, 500);

        whiteCircle();
        text(speed);
        blueCircle(speed);

        setSpeed((prev) => {
          if (prev > 100) prev = 0;
          return (prev += 0.1);
        });
      }
    };
    const draw = window.requestAnimationFrame(drawFrame);
    return () => cancelAnimationFrame(draw);
  }, [context, blueCircle]);

  // Draw a blue outer ring
  function blueCircle(n) {
    context.save();
    context.beginPath();
    context.strokeStyle = "#49f";
    context.lineWidth = 12;
    context.arc(
      centerX,
      centerY,
      100,
      -Math.PI / 2,
      -Math.PI / 2 + n * rad,
      false
    );
    context.stroke();
    context.restore();
  }

  // Draw a white outer ring
  function whiteCircle() {
    context.save();
    context.beginPath();
    context.strokeStyle = "#A5DEF1";
    context.lineWidth = 12;
    context.arc(centerX, centerY, 100, 0, Math.PI * 2, false);
    context.stroke();
    context.closePath();
    context.restore();
  }

  // Percentage Text Drawing
  function text(n) {
    context.save();
    context.fillStyle = "#F47C7C";
    context.font = "40px Arial";
    context.textAlign = "center";
    context.textBaseline = "middle";
    context.fillText(n.toFixed(0) + "%", centerX, centerY);
    context.restore();
  }

  return <canvas id="canvas" ref={canvasRef} width={500} height={500}></canvas>;
};

export default CanvasCircle;


<<:  Day23 React 共享的State(一) Context

>>:  JavaScript Prototype (原型)

[Day17]-应用模组2

时间time模组 使用前要先import time Time()可以传回自1970/1/1以来的秒...

Day 27 讨论 AI 深度学习论点

大家好~~欢迎来到第二十七篇 讨论 AI 我们今日继续说明,关於内轮差产品的由来,因为我们为了处理内...

【Day 17】Google Apps Script - API 篇 - Spreadsheet Service - 电子试算表服务介绍

Spreadsheet(电子试算表) Service API 可以让你完整的控制 Google s...

免费小学堂 | 每日1小时 UiPath 大中华区线上讲堂

RPA人机合作|企业营运未来式|案例分享 日子过得飞快!2022 第一季即将告一段落 若你对於 RP...

Day 1 序言及基本运算元件

我很早就开始接触组合语言,但没有学太久,就没有再碰了,当初学组合语言的原因,是觉得组合语言是人与机器...