怎么在Html5中使用帆布实现一个粒子时钟

  介绍

这篇文章将为大家详细讲解有关怎么在Html5中使用帆布实现一个粒子时钟,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

首先要创建一个html文件并添加一个帆布画布,如下:

& lt; ! DOCTYPE  html>   & lt; html  lang=癳n"祝辞   & lt; head>   ,,,& lt; meta  charset=癠TF-8"比;   ,,,& lt; title> Document   ,,,& lt; style>   ,,,,,,,.container {   ,,,,,,,,,,,保证金:,0,,汽车;   ,,,,,,,,,,,宽度:,600 px;   ,,,,,,,,,,,   ,,,,,,,}   ,,,& lt;/style>   & lt;/head>   & lt; body>   ,,,& lt; div  id=癱ontainer"比;   ,,,,,,,& lt; canvas  id=癱anvas"祝辞& lt;/canvas>   ,,,& lt;/div>   & lt;/body>

下面导入素材,数字。js,素材中通过二维数组拼成一个个数字,共有:0 - 9和冒号,十个字符,如下:

怎么在Html5中使用帆布实现一个粒子时钟

可以看到为1的字符组成了

下面开始创建画布:

function 时钟(),{   ,,,,,,,var  canvas =, . getelementbyid (“canvas");   ,,,,,,,canvas.width =, 600;   ,,,,,,,canvas.height =, 100;   ,,,,,,,this.cxt =, canvas.getContext (& # 39; 2 d # 39;);   ,,,,,,,this.cxt.fillStyle=? ddd";   ,,,,,,,this.cxt.fillRect (0, 0, 500, 100);   ,,,}

上面的代码就可以在浏览器画一个小灰色画布了

下面我们开始分析:

1。了解数据矩阵?就是多维数组

2。如何画圆? <强>

2.1要先知道半径?

怎么在Html5中使用帆布实现一个粒子时钟

由上图得知,圆心的位置依次为:

r + 1   r + 1, +, (r + 1) * 2 * 1   r + 1, +, (r + 1) * 2 * 2   …   r + 1, +, (r + 1) * 2 *我

同时,也可以通过计算圆的高度,得到半径,如下:

一个圆的高度是(r + 1) * 2,画布高度是由10个圆组成

canvasHeight =, (r + 1) * 2 * 10

若将画布高度设为100,则r就出来了,圆心xy也出来了,开始画圆了
先要在上面的时钟对象中加一条语句,计算r

this.r =, 100/20-1;

下面我在时钟的原型上加上画方法

Clock.prototype.draw =,函数(num,指数),{   ,,,,,,,this.cxt.fillStyle=? 000“;;   ,,,,,,,for  (let  i=0, i<数字(num) . length;,我+ +),{   ,,,,,,,,,,,for  (let  j=0, j<数字(num)[我]. length;, j + +), {   ,,,,,,,,,,,,,,,if (数字(num)[我][j],==, 1), {   ,,,,,,,,,,,,,,,,,,,this.cxt.beginPath ();   ,,,,,,,,,,,,,,,,,,,this.cxt.arc(指数* 70 + (this.r + 1) + (this.r + 1) * 2 * j, (this.r + 1) + (this.r + 1) * 2 *我,this.r,, 0,, Math.PI * 2,,假);   ,,,,,,,,,,,,,,,,,,,this.cxt.closePath ();   ,,,,,,,,,,,,,,,,,,,this.cxt.fill ();   ,,,,,,,,,,,,,,,}   ,,,,,,,,,,,}   ,,,,,,,}   ,,,}

画接收2个参数,第一个是字符索引,第二个是字符偏移顺序,70就是一个偏移距离,可以自定。
第一个,拿到要渲染的字符数组,第二个,取每一行进行渲染且只渲染为1的,画圆的参数主要是x, y, r

下面就要得到时间,我们可以直接从新的日期中用正则取时间,如下:

Clock.prototype.getTime =,()函数,{   ,,,,,,,var  reg =,/(\ d) (\ d): (\ d) (\ d): (\ d) (\ d)/.exec (new 日期());   ,,,,,,,var  data =, [];   ,,,,,,,data.push(注册[1],,注册[2],,10日,reg [3],, reg[4],, 10日,reg [5],, reg [6]);   ,,,,,,,for  (var  i=0, i

通过正则可以方便的取到时分秒,在推动数组时注意格式对应,其中10个表示数字。null   null   null   null

怎么在Html5中使用帆布实现一个粒子时钟