JavaScript html5 canvas绘制时钟效果

前端之家收集整理的这篇文章主要介绍了JavaScript html5 canvas绘制时钟效果前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

本文实例讲述了JavaScript+html5 canvas绘制时钟效果分享给大家供大家参考,具体如下:

HTML部分:

<Meta charset="UTF-8"> <Meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0"> canvas绘图

JavaScript部分:

setInterval(function(){draw(canvas,context)},1000);
}
function draw(canvas,context){
var x = canvas.width,y = canvas.height,r = Math.min(x/2,y/2);

context.clearRect(0,x,y); //清除绘画历史
//绘画钟框
context.fillStyle = "#f1f1f1";
drawCircle(context,y,r);
//绘画文字
var tx = x/2,ty = y/2,tr = 0.8r;
context.font = "bold 12px 微软雅黑";
context.fillStyle = "#000";
drawText(context,"1",tx + 0.5
tr,ty - 0.866tr);
drawText(context,"2",tx + 0.866
tr,ty - 0.5tr);
drawText(context,"3",tx + tr,ty);
drawText(context,"4",ty + 0.5
tr);
drawText(context,"5",ty + 0.866tr);
drawText(context,"6",tx,ty + tr);
drawText(context,"7",tx - 0.5
tr,"8",tx - 0.866tr,"9",tx - tr,"10","11","12",ty - tr);
//获取当前时间
var date = new Date(),h = date.getHours(),m = date.getMinutes(),s = date.getSeconds(),angleH = (360/12)
Math.PI/180,angleM = (360/60)Math.PI/180
context.strokeSyle = "#000";
//绘制时刻度
drawScale(context,r,angleH,-0.88
r,-0.96r,3);
//绘制分刻度
drawScale(context,angleM,-0.93
r,1);
//绘画时分秒针
drawCircle(context,3);
drawNeedle(context,hangleH + mangleM/12,-0.5r);
drawNeedle(context,m
angleM + sangleM/60,-0.6r);
drawNeedle(context,sangleM,-0.75r);

}
//绘画圆
function drawCircle(context,r){
context.save();
context.beginPath();
context.arc(x/2,y/2,Math.PI2,0);
context.fill();
context.closePath();
context.restore();
}
//绘画文字方法
function drawText(context,text,y){
context.save();
x -= (context.measureText(text).width/2);
y += 4;
context.translate(x,y);
context.fillText(text,0);
context.restore();
}
//绘制刻度方法
function drawScale(context,rotate,start,end,lineWidth){
context.save();
context.beginPath();
context.translate(x/2,y/2);
context.lineWidth = lineWidth;
for (var i = 0; i < 60; i++) {
context.rotate(rotate);
context.moveTo(0,start);
context.lineTo(0,end);
}
context.closePath();
context.stroke();
context.restore();
}
//绘画时分秒针方法
function drawNeedle(context,line){
context.save();
context.translate(x/2,y/2);
context.beginPath();
context.rotate(rotate);
context.moveTo(0,0.1
r);
context.lineTo(0,line);
context.closePath();
context.stroke();
context.restore();
}

希望本文所述对大家JavaScript程序设计有所帮助。

原文链接:https://www.f2er.com/js/49875.html

猜你在找的JavaScript相关文章