h5 Canvas实现圆形时间倒计时进度条

Posted suwu150

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了h5 Canvas实现圆形时间倒计时进度条相关的知识,希望对你有一定的参考价值。

在项目中,我们会遇到需要显示进度条或者倒计时的功能,我们今天就来实现一下。

一、效果展示


实现效果要求:
1.环形倒计时
2.能够根据总时间和当前时间进行比例性的倒计时
3.进度条环形能够有颜色渐变效果
4.中间文字能够有颜色渐变效果

二、准备文件

在开发canvas程序时,我们通常需要准备静态html和需要引用的js文件即可,这次我们使用的静态html模板如下:
1.html页面

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <!-- <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" /> -->
    <title>圆形倒计时</title>
  </head>
  <body>
    <div class="clock-show" style="width: 800px;height: 700px">
        <canvas id="canvas" width="800" height="700"></canvas>
      </div>
  </body>

  <script src="./index.js"></script>
</html>

2.js文件-需要操作canvas标签的代码
我们先定义好需要去实现的方法,分别如下面代码

function CircleClock(canvas) 
  // 定义一个CircleClock构造函数,用于初始化 


CircleClock.prototype.setProgress = function (progress) 
    // 用于设置从外部设置进度
;

CircleClock.prototype.getProgress = function () 
    // 用于获取进度
;

CircleClock.prototype.drawBackgroundCircle = function () 
    // 画圆形的背景环形条
;

CircleClock.prototype.drawCurrentProgressCircle = function () 
  // 绘制倒计时环形进度条
;

CircleClock.prototype.createLinearGradientByTime = function () 
    // 按照进度,计算渐变色
;

CircleClock.prototype.drawTimeText = function () 
    // 绘制环中间文字倒计时
;

CircleClock.prototype.clear = function () 
    // 清理canvas
;

CircleClock.prototype.setTime = function (seconds) 
    // 设置初始时间,需要倒计时的时间
;

CircleClock.prototype.setCurrentTime = function (currentSeconds) 
    // 实时同步当前剩下的时间
;

CircleClock.prototype.run = function (seconds, endCallback) 
    // 开始运行项目,运行时传入初始时间和回调函数
;

CircleClock.prototype.update = function (unPass) 
  this.setCurrentTime(unPass);
  this.clear();
  this.drawBackgroundCircle();
  this.drawCurrentProgressCircle();
  this.drawTimeText();
;

const circleClock = new CircleClock("canvas");
circleClock.run(30, () => 
  console.log("倒计时执行完毕");
);

三、代码方法说明

1.构造函数
function CircleClock(canvas) 
  // 定义一个CircleClock构造函数,用于初始化 
  this.canvas = document.querySelector(canvas);
  this.context = this.canvas.getContext("2d");
  this.width = 800;
  this.height = 700;
  this.progress = 0;  // 用于记录当前的进度
  this.seconds = 0; // 需要倒计时的时间,秒
  this.currentSeconds = 0; // 当前倒计时到的位置

2.设置进度和获取进度方法
CircleClock.prototype.setProgress = function (progress) 
    // 用于设置从外部设置进度
  this.progress = progress;
;
CircleClock.prototype.getProgress = function () 
    // 用于获取进度
  return this.progress;
;
3.绘制圆形进度背景环
CircleClock.prototype.drawBackgroundCircle = function () 
    // 画圆形的背景环形条
  const x = this.width / 2;
  const y = this.height / 2;
  this.context.strokeStyle = "#40C4FF";
  this.context.lineWidth = 16;
  this.context.beginPath();
  // 绘制圆形背景。从弧度-(Math.PI / 2)到2 * Math.PI
  this.context.arc(x, y, this.width / 5, -(Math.PI / 2), 2 * Math.PI);
  this.context.stroke();
;
4.绘制当前进度环
CircleClock.prototype.drawCurrentProgressCircle = function () 
  const x = this.width / 2;
  const y = this.height / 2;
  // 绘制倒计时环形进度条
  const canvasGradient = this.context.createLinearGradient(
    0,
    0,
    0,
    this.height
  );
  // 在offset为0的位置(即起点位置)添加一个蓝色的渐变
  canvasGradient.addColorStop(0, "#00BCD4");
  // 在offset为0.4的位置(线段左起20%的位置)添加一个绿色的渐变
  canvasGradient.addColorStop(0.4, "#7C4DFF");
  // 在offset为0.8的位置(即终点位置)添加一个红色的渐变
  canvasGradient.addColorStop(0.8, "#DCE775");
  // 在offset为1的位置(即终点位置)添加一个红色的渐变
  canvasGradient.addColorStop(1, "#FF5722");
  // 将strokeStyle的属性值设为该CanvasGradient对象
  this.context.strokeStyle = canvasGradient;
  // 计算进度
  const progress = 1 - this.currentSeconds / this.seconds;
  this.setProgress(progress);
  // - (Math.PI/2),  (progress) *(3/2 *Math.PI)   [-0.5, 1.5]-[0, 1],
  this.context.lineWidth = 16;
  this.context.lineCap = "round";
  this.context.beginPath();
  // 绘制圆形进度环
  this.context.arc(
    x,
    y,
    this.width / 5,
    -(Math.PI / 2),
    (-0.5 + 2 * progress) * Math.PI
  );
  this.context.stroke();
;
5.根据时间或者进度创建渐变色
CircleClock.prototype.createLinearGradientByTime = function () 
    // 按照进度,计算渐变色
  const progress = this.getProgress();
  // 修改填充颜色
  const canvasGradient = this.context.createLinearGradient(
    this.width / 2 - 18,
    this.height / 2 - 18,
    this.width / 2,
    this.height / 2 + 50
  );
  canvasGradient.addColorStop(0, "#00BCD4");
  progress > 0 && progress < 0.4 && canvasGradient.addColorStop(0.3, "#7C4DFF");

  progress > 0.4 &&
    progress < 0.8 &&
    canvasGradient.addColorStop(0.6, "#DCE775");
  progress > 0.6 &&
    progress < 0.9 &&
    canvasGradient.addColorStop(0.8, "#EEFF41");
  canvasGradient.addColorStop(1, "#FF5722");
  return canvasGradient;
;
6.绘制中间的倒计时文本
CircleClock.prototype.drawTimeText = function () 
    // 绘制环中间文字倒计时
  this.context.fillStyle = this.createLinearGradientByTime();
  this.context.textAlign = "start";
  this.context.font = "36px bold";
  this.context.textBaseline = "alphabetic";
  let s = parseInt(this.currentSeconds);
  let ss = parseInt(s % 60);
  let mm = parseInt(s / 60);
  const text = `$mm.toString().padStart(2, 0): $ss
    .toString()
    .padStart(2, 0)`;
    // 计算文本长度,适配位置
  const textWidth = this.context.measureText(text).width;
  this.context.fillText(
    text,
    this.width / 2 - textWidth / 2,
    this.height / 2 + 18
  );
;

7.清理canvas
CircleClock.prototype.clear = function () 
    // 清理canvas
  this.context.clearRect(0, 0, this.width, this.height); //每改变一次动画就要对这个空间范围进行一次刷新,不然会重叠在一起
;
8.设置初始倒计时时间
CircleClock.prototype.setTime = function (seconds) 
    // 设置初始时间,需要倒计时的时间
  this.seconds = seconds;
;
9.设置当前已经倒计时的时间点
CircleClock.prototype.setCurrentTime = function (currentSeconds) 
    // 实时同步当前剩下的时间
  this.currentSeconds = currentSeconds;
;
10.开始运行项目

运行项目,传入初始时间和回调函数,这里会不停的反复运行,如果需要停止,可以通过打开clearInterval(intervalTime);代码进行关闭计时器

CircleClock.prototype.run = function (seconds, endCallback) 
    // 开始运行项目,运行时传入初始时间和回调函数
  let count = 0;
  const intervalTime = setInterval(() => 
    this.setTime(seconds);
    const allTime = this.seconds;
    const unPass = allTime - count;
    count = count + 1;
    console.log("unPass", unPass);
    if (unPass < 0) 
      //   clearInterval(intervalTime);
      this.setTime(30);
      count = 0;
      endCallback && endCallback();
     else 
      this.update(unPass);
    
  , 1000);
;
11.更新时间

用于更新当前已经倒计时倒计到的时间,相当于重新绘制整个界面

CircleClock.prototype.update = function (unPass) 
  this.setCurrentTime(unPass);
  this.clear();
  this.drawBackgroundCircle();
  this.drawCurrentProgressCircle();
  this.drawTimeText();
;
12.初始化,运行代码

const circleClock = new CircleClock("canvas");
circleClock.run(30, () => 
  console.log("倒计时执行完毕");
);

上面是所有代码的分布解析,下面给出完整代码

四、完整代码

1.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <!-- <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" /> -->
    <title>圆形倒计时</title>
  </head>
  <body>
    <div class="clock-show" style="width: 800px;height: 700px">
        <canvas id="canvas" width="800" height="700"></canvas>
      </div>
  </body>

  <script src="./index.js"></script>
</html>

2.js

function CircleClock(canvas) 
  // 定义一个CircleClock构造函数,用于初始化 
  this.canvas = document.querySelector(canvas);
  this.context = this.canvas.getContext("2d");
  this.width = 800;
  this.height = 700;
  this.progress = 0;  // 用于记录当前的进度
  this.seconds = 0; // 需要倒计时的时间,秒
  this.currentSeconds = 0; // 当前倒计时到的位置


CircleClock.prototype.setProgress = function (progress) 
    // 用于设置从外部设置进度
  this.progress = progress;
;

CircleClock.prototype.getProgress = function () 
    // 用于获取进度
  return this.progress;
;

CircleClock.prototype.drawBackgroundCircle  = function () 
    // 画圆形的背景环形条
  const x = this.width / 2;
  const y = this.height / 2;
  this.context.strokeStyle = "#40C4FF";
  this.context.lineWidth = 16;
  this.context.beginPath();
  // 绘制圆形背景。从弧度-(Math.PI / 2)到2 * Math.PI
  this.context.arc(x, y, this.width / 5, -(Math.PI / 2), 2 * Math.PI);
  this.context.str

以上是关于h5 Canvas实现圆形时间倒计时进度条的主要内容,如果未能解决你的问题,请参考以下文章

h5canvas圆形进度条上上有圆点,进度70%圆点就在70%上(随着进度到哪就在哪),怎么做。

圆形进度条:简单实现倒计时圆形进度条

圆形进度条 Android

自定义圆形进度条 自定义倒计时进度条

HTML+CSS+JS实现 ❤️canvas圆形水波进度条动画特效❤️

HTML+CSS+JS实现 ❤️canvas圆形水波进度条动画特效❤️