HTML5之时钟

近来接触了一点HTML5,写个时钟分享一下。

上次忘记发图补一下

/**

 * HTML5 时钟

 * @author jason.zhou

 * @email neimengxiaohuo@gmail.com

 * @date 2011.3.30

 */

/**

 * Constructor 时钟构造器

 * @param ctx HTML DOM CanvasRenderingContext2D 对象

 */

function Clock(ctx){

this.ctx = ctx;

this.drawOutline(100);

this.go();

}

/**

 * 绘制时钟的轮廓

 * @param r 表盘半径

 */

Clock.prototype.drawOutline = function(r){

this.ctx.strokeStyle = 'black';

this.ctx.font = "12pt Arial";

this.ctx.textBaseline  = 'top';

for(var i = 0; i < 60; i++){

var x = 200 + Math.sin(i/60*2*Math.PI)*r;

var y = 200 - Math.cos(i/60*2*Math.PI)*r;

if(i%5 == 0){

this.ctx.fillText(i != 0 ? i/5 : 12 , x - 6.5 , y - 6.5);

}

}

}

/**

 * 绘制时钟的轮廓

 * @param pointerOffset 指针偏移量

 * @param pointerLength 指针长度

 * @param pointerWidth 指针宽度

 */

Clock.prototype.drawPointer = function(pointerOffset, pointerLength, pointerWidth){

this.ctx.save();

this.ctx.fillStyle = 'black';

this.ctx.lineWidth = pointerWidth || 1;

var x = 200 + Math.sin(pointerOffset*2*Math.PI)*pointerLength;

var y = 200 - Math.cos(pointerOffset*2*Math.PI)*pointerLength;

this.ctx.beginPath();

this.ctx.moveTo(200 , 200);

this.ctx.lineTo(x , y);

this.ctx.stroke();

this.ctx.restore();

}

/**

 * 启动

 */

Clock.prototype.go = function(){

var me = this;

this.drawCurrentTime();

window.setInterval(function(){

me.drawCurrentTime();

}, 1000);

}

/**

 * 绘制当前时间

 */

Clock.prototype.drawCurrentTime = function(){

this.ctx.fillStyle ='white';

this.ctx.beginPath();

this.ctx.arc(200, 200, 80, 0, 2*Math.PI, true); 

this.ctx.fill();

var date = new Date();

var h = date.getHours() > 12 ? date.getHours()-12 : date.getHours();

var m = date.getMinutes();

var s = date.getSeconds();

this.drawPointer(h/12, 50, 4);

this.drawPointer(m/60, 60, 2);

this.drawPointer(s/60, 80);

}

demo下载

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值