亲宝软件园·资讯

展开

JavaScript canvas

用户4811483110569​​​​​​​ 人气:0

前言

内容:

1、效果图展示

(img-iSl2hFK6-1605966576712)(./images/1.png)]

随着时间的减少, 圆环的红黄色部分会慢慢的减少,圆环中的数字会变小,一直到0停止.

2、需求分析

3、实现的技术

语言框架
HTML5
CSS3BootStrap SASS
JavaScript

4、实现的过程

1. HTML 部分

主要用到的是 HTML5 中的画布元素 canvas, 一共4个 canvas 元素拍成一排, 每个元素都是高144px, 宽144px的正方形, 两个圆环中的两个小点部分可以使用伪元素 after 和 before 来实现

源码如下:

<div class="count-down">
 <div class="container">
   <div class="row">
     <div class="days col-lg-3 col-md-3 col-sm-3 col-xs-6">
       <div class="colck">
         <canvas id="days" width="144" height="144"></canvas>
       </div>
     </div>
     <div class="hours col-lg-3 col-md-3 col-sm-3 col-xs-6">
       <div class="colck">
         <canvas id="hours" width="144" height="144"></canvas>
       </div>
     </div>
     <div class="minutes col-lg-3 col-md-3 col-sm-3 col-xs-6">
       <div class="colck">
         <canvas id="minutes" width="144" height="144"></canvas>
       </div>
     </div>
     <div class="seconds col-lg-3 col-md-3 col-sm-3 col-xs-6">
       <div class="colck">
         <canvas id="seconds" width="144" height="144"></canvas>
       </div>
     </div>
   </div>
 </div>
</div>

用 BootStrap 提供的栅格布局快速的把 canvas 元素排成一排 为每个 cnavas 元素设置对应的 id, 方便用 JavaScript 获取到该元素.

2. SASS部分

css 的部分是用 Sass 来写的, Sass 是一个 css 的 扩展语言, html 文件中引用的是写好的 Sass 文件编译生成 css 文件.

源码如下:

.count-down {
  width: 100%;
  .row {
    padding: 0 145px;
  }
  .col-lg-3 {
    padding: 0;
    position: relative;
    .colck {
      width: 144px;
      height: 144px;
      background-color: #fff;
      margin: 0 auto;
    }
  }
  .days, .hours, .minutes {
    &:after, &:before {
      content: "";
      display: block;
      width: 12px;
      height: 12px;
      background-color: #fff;
      position: absolute;
      right: -6px;
    }
    &:after {
      bottom: 45px;
    }
    &:before {
      top: 45px;
    } 
  }
}

控制圆环的运动主要靠 JavaScript 代码, 这里 sass 的作用是用来把把元素的位置排列好, 把两个圆环中间的点画出来,

因为背景色是黑色的 为了看的更加直观, 我先把包裹 canvas 的元素背景色设为白色,

此时的效果: 

在这里插入图片描述

3. JavaScript部分

最终的运动效果靠 js 代码来实现:

// 获取4个 canvas 元素
var days_canvas = document.getElementById('days');
var hours_canvas = document.getElementById('hours');
var minutes_canvas = document.getElementById('minutes');
var seconds_canvas = document.getElementById('seconds');
// 设置倒计时时间:年 月 日 小时 分钟 秒 毫秒
endTime = setEndTime(2020, 11, 30, 15, 0, 0);

// 设置到期时间
function setEndTime(year, month, day, hour, minute, millisecond) {
return new Date(year, month - 1, day, hour, minute, millisecond);
}

js 中创建 Date 对象的5种方式 new Date("month dd,yyyy hh:mm:ss"); new Date("month dd,yyyy"); new Date(yyyy,mth,dd,hh,mm,ss); new Date(yyyy,mth,dd); new Date(ms);

注意: Date 对象中的月份取值是 0 - 11, 0 就表示 1 月, 用变量 endTime 保存这个设置好的 Date 对象

// 计算距离到期时间还剩下多少 days, hours, minutes
 function getLeftTimeObj() {
   var date = new Date();
   var millisecond = date.getTime()
   var end_millisecond = endTime.getTime();

   if (end_millisecond < millisecond) {
     return {
       days: 0,
       hours: 0,
       minutes: 0,
       seconds: 0
     }
   }
   // 距离结束时间的秒数
   var left_seconds = (( end_millisecond - millisecond ) / 1000);
   var seconds = (left_seconds % 60);
   var left_minutes = (left_seconds - seconds) / 60;
   var minutes = (left_minutes % 60);
   var left_hours = (left_minutes - minutes) / 60;
   var hours = (left_hours % 24);
   var left_days = ((left_hours - hours) / 24);

   return {
     days: left_days,
     hours: hours,
     minutes: minutes,
     seconds: seconds
   }
 }
 var dateObj = getLeftTimeObj();

思路:

我们定义一个变量 dateObj 保存这个对象, 然后根据这个对象去在相应的 canvas 元素上画图

我们先不考虑怎么让圆环动起来, 而是先考虑怎么把图画出来

观察单个图形的样子如下图所示:

在这里插入图片描述

可以把这个图形分成4个部分:

我们可以为写四个方法分别完成每一个步骤:

 // 画整个圆
function drawCricle(canvas) {
  // 获取 context 对象
  var context = canvas.getContext('2d');
  // 获取 canvas 的中心点的 x 坐标
  var centerX = canvas.width / 2;
  // 获取 canvas 的中心点的 y 坐标
  var centerY = canvas.height / 2;
  context.save();
  context.beginPath();
  context.lineWidth = 7;
  context.strokeStyle = "#636363";
  // 圆环的宽度为 7, canvas 元素的长和宽是 144, 所以圆半径应为 (144 - 7) / 2, 也就是 canvas.width / 2 - 3.5
  context.arc(centerX, centerY, canvas.width / 2 - 3.5 , 0, Math.PI*2, false);
  context.stroke();
  context.closePath();
  context.restore();
}

// 画数字下的字符
function drawStr(canvas, str) {
  var context = canvas.getContext('2d');
  var centerX = canvas.width / 2;
  var centerY = canvas.height / 2;

  context.save();
  context.fillStyle = '#fff';
  context.font = "14px Arial"; //设置字体大小和字体
  context.textAlign = 'center';
  context.fillText(str, centerX, centerY+54);
  context.restore();
}

// 画数字
function drawNumber(canvas, num) {
  var context = canvas.getContext('2d');
  var centerX = canvas.width / 2;
  var centerY = canvas.height / 2;
  num = num.toFixed();
  num = num < 10 ? '0' + num : num;

  context.save();
  context.fillStyle = '#fff';
  context.font = "bolder 60px Arial"; //设置字体大小和字体
  context.textAlign = 'center';
  // context.fontWeight = 'bold';
  context.fillText(num, centerX, centerY+10);
  context.restore();
}
// 画进度条 -0.5为起点
// percentage 为进度条的百分比(0<percentage<1), 1 表示整个圆
function drawProgress(canvas, percentage) {
  var context = canvas.getContext('2d');
  var centerX = canvas.width / 2;
  var centerY = canvas.height / 2;

  var end_cricle = (percentage * 2) - 0.5;
  end_cricle = Number(end_cricle.toFixed(4))

  // 设置垂直渐变
  var linearGrad = context.createLinearGradient(canvas.width / 2, 0, canvas.width / 2, canvas.height);
  linearGrad.addColorStop(0, '#ff0503');
  linearGrad.addColorStop(1, '#ff8200');

  context.save();
  context.strokeStyle = linearGrad; //设置描边样式
  context.lineWidth = 7; //设置线宽
  context.beginPath(); //路径开始
  context.arc(centerX, centerY, canvas.width / 2 -3.5 , -0.5 * Math.PI, end_cricle * Math.PI, false); //用于绘制圆弧context.arc(x坐标,y坐标,半径,起始角度,终止角度,顺时针/逆时针)
  context.stroke(); //绘制
  context.closePath(); //路径结束
  context.restore();
}
// 为秒计数的 canvas 绘图, 画图依赖 dateObj.seconds
drawCricle(seconds_canvas);
drawStr(seconds_canvas, 'Seconds');
// 每一分钟有60秒, 用 dateObj.seconds / 60 获得 当前进度
drawProgress(seconds_canvas, (dateObj.seconds / 60).toFixed(4));
drawNumber(seconds_canvas, dateObj.seconds);

写一个绘制 4 个 canvas 的方法 draw(); 然后执行

// 绘图
function draw() {
  drawCricle(days_canvas);
  drawStr(days_canvas, 'Days');
  drawProgress(days_canvas, dateObj.days / 10);
  drawNumber(days_canvas, dateObj.days);

  drawCricle(hours_canvas);
  drawStr(hours_canvas, 'Hours');
  drawProgress(hours_canvas, (dateObj.hours / 24).toFixed(4));
  drawNumber(hours_canvas, dateObj.hours);

  drawCricle(minutes_canvas);
  drawStr(minutes_canvas, 'Minutes');
  drawProgress(minutes_canvas, (dateObj.minutes / 60).toFixed(4));
  drawNumber(minutes_canvas, dateObj.minutes);

  drawCricle(seconds_canvas);
  drawStr(seconds_canvas, 'Seconds');
  drawProgress(seconds_canvas, (dateObj.seconds / 60).toFixed(4));
  drawNumber(seconds_canvas, dateObj.seconds);
}

drwa();

然后先记得把之前设置的白色背景色去掉

执行了 draw() 之后效果如下图: 

在这里插入图片描述

但是现在还没有实现让他动起来,

先明白动起来的逻辑:

// 清除 canvas 内容
function clear() {
  var days_ctx = days_canvas.getContext('2d');
  var hours_ctx = hours_canvas.getContext('2d');
  var minutes_ctx = minutes_canvas.getContext('2d');
  var seconds_ctx = seconds_canvas.getContext('2d');

  days_ctx.clearRect(0, 0, days_canvas.width, days_canvas.height);
  hours_ctx.clearRect(0, 0, hours_canvas.width, hours_canvas.height);
  minutes_ctx.clearRect(0, 0, minutes_canvas.width, minutes_canvas.height);
  seconds_ctx.clearRect(0, 0, seconds_canvas.width, seconds_canvas.height);
}
// 让倒计时动起来
// 可以直接用定时器
setInterval(function() {
  clear();
  dateObj = getLeftTimeObj();
  draw();
}, 16)

// 也可以考虑使用 requestAnimationFrame 这个方法
(function count() {
  requestAnimationFrame(count);
  clear();
  dateObj = getLeftTimeObj();
  draw();
})();

到现在为止整个完整的功能全部实现了。

5、全部源码

1.index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="./bootstrap.min.css" rel="external nofollow" >
  <link rel="stylesheet" href="./style.css" rel="external nofollow" >
  <style>
    .count-down {
      background: #000;
    }
  </style>
</head>
<body>
  <div class="count-down">
    <div class="container">
      <div class="row">
        <div class="days col-lg-3 col-md-3 col-sm-3 col-xs-6">
          <div class="colck">
            <canvas id="days" width="144" height="144"></canvas>
          </div>
        </div>
        <div class="hours col-lg-3 col-md-3 col-sm-3 col-xs-6">
          <div class="colck">
            <canvas id="hours" width="144" height="144"></canvas>
          </div>
        </div>
        <div class="minutes col-lg-3 col-md-3 col-sm-3 col-xs-6">
          <div class="colck">
            <canvas id="minutes" width="144" height="144"></canvas>
          </div>
        </div>
        <div class="seconds col-lg-3 col-md-3 col-sm-3 col-xs-6">
          <div class="colck">
            <canvas id="seconds" width="144" height="144"></canvas>
          </div>
        </div>
      </div>
    </div>
  </div>
  <script src="./index.js"></script>
</body>
</html>

2. style.scss

.count-down {
  position: absolute;
  bottom: 90px;
  left: 0;
  width: 100%;
  .row {
    padding: 0 145px;
  }
  .col-lg-3 {
    padding: 0;
    position: relative;
    .colck {
      width: 144px;
      height: 144px;
      // background-color: #fff;
      margin: 0 auto;
    }
  }
  .days, .hours, .minutes {
    &:after, &:before {
      content: "";
      display: block;
      width: 12px;
      height: 12px;
      background-color: #fff;
      position: absolute;
      right: -6px;
    }
    &:after {
      bottom: 45px;
    }
    &:before {
      top: 45px;
    } 
  }
}

3. index.js

// 倒计时
// 到期时间
// 设置倒计时时间:年 月 日 小时 分钟 秒 毫秒
endTime = setEndTime(2020, 11, 30, 15, 0, 0);

// 设置到期时间
function setEndTime(year, month, day, hour, minute, millisecond) {
  return new Date(year, month - 1, day, hour, minute, millisecond);
}

// 获取4个 canvas 元素
var days_canvas = document.getElementById('days');
var hours_canvas = document.getElementById('hours');
var minutes_canvas = document.getElementById('minutes');
var seconds_canvas = document.getElementById('seconds');

// 计算距离到期时间还剩下多少 days, hours, minutes
function getLeftTimeObj() {
  var date = new Date();
  var millisecond = date.getTime()
  var end_millisecond = endTime.getTime();

  if (end_millisecond < millisecond) {
    return {
      days: 0,
      hours: 0,
      minutes: 0,
      seconds: 0
    }
  }

  // 距离结束时间的秒数
  var left_seconds = (( end_millisecond - millisecond ) / 1000);

  var seconds = (left_seconds % 60);
  var left_minutes = (left_seconds - seconds) / 60;
  var minutes = (left_minutes % 60);
  var left_hours = (left_minutes - minutes) / 60;
  var hours = (left_hours % 24);
  var left_days = ((left_hours - hours) / 24);

  return {
    days: left_days,
    hours: hours,
    minutes: minutes,
    seconds: seconds
  }
}

var dateObj = getLeftTimeObj();

// 画整个圆
function drawCricle(canvas) {
  var context = canvas.getContext('2d');
  var centerX = canvas.width / 2;
  var centerY = canvas.height / 2;

  context.save();
  context.beginPath();
  context.lineWidth = 7;
  context.strokeStyle = "#636363";
  context.arc(centerX, centerY, canvas.width / 2 - 3.5 , 0, Math.PI*2, false);
  context.stroke();
  context.closePath();
  context.restore();
}

// 画数字下的字符
function drawStr(canvas, str) {
  var context = canvas.getContext('2d');
  var centerX = canvas.width / 2;
  var centerY = canvas.height / 2;

  context.save();
  context.fillStyle = '#fff';
  context.font = "14px Arial"; //设置字体大小和字体
  context.textAlign = 'center';
  context.fillText(str, centerX, centerY+54);
  context.restore();
}

// 画数字
function drawNumber(canvas, num) {
  var context = canvas.getContext('2d');
  var centerX = canvas.width / 2;
  var centerY = canvas.height / 2;
  num = num.toFixed();
  num = num < 10 ? '0' + num : num;

  context.save();
  context.fillStyle = '#fff';
  context.font = "bolder 60px Arial"; //设置字体大小和字体
  context.textAlign = 'center';
  // context.fontWeight = 'bold';
  context.fillText(num, centerX, centerY+10);
  context.restore();
}

// 画进度条 -0.5为起点
// percentage 为进度条的百分比(0<percentage<1), 1 表示整个圆
function drawProgress(canvas, percentage) {
  var context = canvas.getContext('2d');
  var centerX = canvas.width / 2;
  var centerY = canvas.height / 2;

  var end_cricle = (percentage * 2) - 0.5;
  end_cricle = Number(end_cricle.toFixed(4))

  // 设置垂直渐变
  var linearGrad = context.createLinearGradient(canvas.width / 2, 0, canvas.width / 2, canvas.height);
  linearGrad.addColorStop(0, '#ff0503');
  linearGrad.addColorStop(1, '#ff8200');

  context.save();
  context.strokeStyle = linearGrad; //设置描边样式
  context.lineWidth = 7; //设置线宽
  context.beginPath(); //路径开始
  context.arc(centerX, centerY, canvas.width / 2 -3.5 , -0.5 * Math.PI, end_cricle * Math.PI, false); //用于绘制圆弧context.arc(x坐标,y坐标,半径,起始角度,终止角度,顺时针/逆时针)
  context.stroke(); //绘制
  context.closePath(); //路径结束
  context.restore();
}

// 清除 canvas 内容
function clear() {
  var days_ctx = days_canvas.getContext('2d');
  var hours_ctx = hours_canvas.getContext('2d');
  var minutes_ctx = minutes_canvas.getContext('2d');
  var seconds_ctx = seconds_canvas.getContext('2d');

  days_ctx.clearRect(0, 0, days_canvas.width, days_canvas.height);
  hours_ctx.clearRect(0, 0, hours_canvas.width, hours_canvas.height);
  minutes_ctx.clearRect(0, 0, minutes_canvas.width, minutes_canvas.height);
  seconds_ctx.clearRect(0, 0, seconds_canvas.width, seconds_canvas.height);
}

// 绘图
function draw() {
  drawCricle(days_canvas);
  drawCricle(hours_canvas);
  drawCricle(minutes_canvas);
  drawCricle(seconds_canvas);
  drawStr(days_canvas, 'Days');
  drawStr(hours_canvas, 'Hours');
  drawStr(minutes_canvas, 'Minutes');
  drawStr(seconds_canvas, 'Seconds');

  drawProgress(days_canvas, dateObj.days / 10 >= 1 ? 1 : dateObj.days / 10);
  drawNumber(days_canvas, dateObj.days);
  drawProgress(hours_canvas, (dateObj.hours / 24).toFixed(4));
  drawNumber(hours_canvas, dateObj.hours);
  drawProgress(minutes_canvas, (dateObj.minutes / 60).toFixed(4));
  drawNumber(minutes_canvas, dateObj.minutes);
  drawProgress(seconds_canvas, (dateObj.seconds / 60).toFixed(4));
  drawNumber(seconds_canvas, dateObj.seconds);
}

draw();

(function count() {
  requestAnimationFrame(count);
  clear();
  dateObj = getLeftTimeObj();
  draw();
})();

加载全部内容

相关教程
猜你喜欢
用户评论