﻿ Html5 canvas实现粒子时钟的示例代码 - 鸿网互联

# Html5 canvas实现粒子时钟的示例代码

```<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>Document</title>
<style>
.container{
margin: 0, auto;
width: 600px;

}
</style>
<body>
<p id="container">
<canvas id="canvas"></canvas>
</p>
</body>```

```function Clock() {
var canvas = document.getElementById("canvas");
canvas.width = 600;
canvas.height = 100;
this.cxt = canvas.getContext('2d');
this.cxt.fillStyle="#ddd";
this.cxt.fillRect(0, 0, 500, 100);
}```

1.了解数据矩阵？就是多维数组

2.如何画圆？

2.1要先知道半径？

```r+1
r+1 + (r+1)*2*1
r+1 + (r+1)*2*2
。。。
r+1 + (r+1)*2*i```

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

`this.r = 100/20-1;`

```Clock.prototype.draw = function(num, index) {
this.cxt.fillStyle="#000";
for (let i=0; i<digit[num].length; i++) {
for (let j=0; j<digit[num][i].length; j++) {
if (digit[num][i][j] == 1) {
this.cxt.beginPath();
this.cxt.arc(index*70+(this.r+1)+(this.r+1)*2*j, (this.r+1)+(this.r+1)*2*i, this.r, 0, Math.PI*2, false);
this.cxt.closePath();
this.cxt.fill();
}
}
}
}```

draw接收2个参数，第一个是字符索引，第二个是字符偏移顺序，70就是一个偏移距离，可以自定。

```Clock.prototype.getTime = function() {
var reg = /(\d)(\d):(\d)(\d):(\d)(\d)/.exec(new Date());
var data = [];
data.push(reg[1], reg[2], 10, reg[3], reg[4], 10, reg[5], reg[6]);
for (var i=0; i<data.length; i++) {
this.draw(data[i], i);
}
}```

`canvas.height= 100`

```var clock = new Clock();
setInterval(()=>{
clock.getTime();
})```

php公益培训视频教程

HTML5图文教程

HTML5在线手册

<