本文主要包含HTML5等相关知识,匿名希望在学习及工作中可以帮助到您

就是这个数字时钟,当时觉得这个创意不错,但是也没去折腾。直到昨天同事又在网上看到这个案例,他觉得很酷炫,就跑过来问我,这个是怎么实现的,然后我大概想了一下实现方法后也来了点兴趣,就花了一点时间模仿做出来了一个。不同的是,岑安用的是div来做的。而我就是用canvas来实现的。用canvas来做性能方面会更好,因为就单单操控每个点的运动,用js控制dom的style属性跟用js控制canvas绘图相比性能方面肯定是有所欠缺的。
先上个我做的DEMO吧,然后再简述一下做这个的方法: 看DEMO请戳我 。
做这个思路很简单,就是通过字符串保存各个数字的位置:
复制代码
- var numData = [
- "1111/1001/1001/1001/1001/1001/1111", //0
- "0001/0001/0001/0001/0001/0001/0001", //1
- "1111/0001/0001/1111/1000/1000/1111", //2
- "1111/0001/0001/1111/0001/0001/1111", //3
- "1010/1010/1010/1111/0010/0010/0010", //4
- "1111/1000/1000/1111/0001/0001/1111", //5
- "1111/1000/1000/1111/1001/1001/1111", //6
- "1111/0001/0001/0001/0001/0001/0001", //7
- "1111/1001/1001/1111/1001/1001/1111", //8
- "1111/1001/1001/1111/0001/0001/1111", //9
- "0000/0000/0010/0000/0010/0000/0000", //:
- ]
0代表没像素,1代表有像素,/是为了更好看些,就是分行嘛,简单说起来:比如0就是:
- 1 1 1 1
- 1 0 0 1
- 1 0 0 1
- 1 0 0 1
- 1 0 0 1
- 1 0 0 1
- 1 1 1 1
这样就很清楚了吧。从0到9还有一个:号都用字符串表示好。
然后就写个粒子对象,也就是像素点:
- var P_radius = 8,Gravity = 9.8;
- var Particle = function(){
- this.x = 0;
- this.y = 0;
- this.vx = 0;
- this.vy = 0;
- this.color = "";
- this.visible = false;
- this.drop = false;
- }
- Particle.prototype = {
- constructors:Particle,
- paint:function(){ //绘制自身
- ctx.fillStyle = this.color;
- ctx.beginPath();
- ctx.arc(this.x,this.y,P_radius,0,2*Math.PI);
- ctx.fill();
- },
- reset:function(x,y,color){ //重置
- this.x = x;
- this.y = y;
- this.vx = 0;
- this.vy = 0;
- this.color = color;
- this.visible = true;
- this.drop = false;
- },
- isDrop:function(){ //落下
- this.drop = true;
- var vx = Math.random()*20+15
- this.vx = Math.random()>=0.5?-vx : vx;
- },
- update:function(time){ //每一帧的动作
- if(this.drop){
- this.x += this.vx*time;
- this.y += this.vy*time;
- var vy = this.vy+Gravity*time;
- if(this.y>=canvas.height-P_radius){
- this.y = canvas.height-P_radius
- vy = -vy*0.7;
- }
- this.vy = vy;