html5 Canvas 钟表
html5 canvas 画钟表例子,参考别人的例子,整理完成,有详细注释
参考:http://www.html5tricks.com/demo/html5-canvas-circle-clock/index.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <canvas id="myCanvas" width="400" height="400" style="border:5px solid #888;background-color:#edf;"></canvas> </body> </html>
var c = document.getElementById('myCanvas').getContext('2d'); function clock(){ //清空画布 c.clearRect(0,0,400,400); var data = new Date(); var sec =data.getSeconds(); var min =data.getMinutes(); var hour=data.getHours(); var year=data.getFullYear(); var month=data.getMonth()+1; var day =data.getDate(); //保存当前环境的状态 c.save(); //重新映射画布上的 (0,0) 位置 c.translate(200,200); //旋转当前绘图(逆时针旋转1/4的圆路径) c.rotate(-2*Math.PI/4); //分钟刻度线(画60个刻度线) for(var i=0;i<60;i++){ c.beginPath(); c.strokeStyle = "#f00"; c.lineWidth = 5; c.moveTo(110,0); c.lineTo(120,0); c.stroke(); //每个6deg画一个时钟刻度线(顺时针旋转1/60的圆路径) c.rotate(2*Math.PI/60); c.closePath(); } //时钟刻度线(画12个刻度线) for(var i=0;i<12;i++){ c.beginPath(); c.strokeStyle = "#000"; c.lineWidth = 8; c.moveTo(100,0); c.lineTo(120,0); c.stroke(); //每个30deg画一个时钟刻度线(顺时针旋转1/12的圆路径) c.rotate(2*Math.PI/12); c.closePath(); } c.rotate(-1); //时钟刻度数字(画12个刻度数字) for(var i=0;i<12;i++){ c.beginPath(); c.strokeStyle = "blue"; c.lineWidth = 2 ; c.strokeText(i+1,0,90); //每个30deg画一个时钟刻度线 c.rotate(2*Math.PI/12); c.closePath(); } c.rotate(1); //时间显示 c.rotate(2*Math.PI/4); c.font="30px 宋体"; c.strokeText(year+"-"+month+"-"+day+" "+hour+":"+min+":"+sec,-130,180); c.rotate(-2*Math.PI/4); //外表盘 c.beginPath(); c.strokeStyle = "pink"; c.lineWidth = 12 ; //画圆 c.arc(0,0,135,0,Math.PI*2); c.stroke(); c.closePath(); //画时针 hour = hour>12?hour-12:hour; c.beginPath(); //保存当前环境的状态 c.save(); //顺时针旋转当前时针指向所形成的圆弧路径 c.rotate(2*Math.PI/12*hour+2*Math.PI/12/60*min+2*Math.PI/12/3600*sec); c.strokeStyle = "yellowgreen"; c.lineWidth = 4; c.moveTo(-20,0); c.lineTo(50,0); c.stroke(); //返回之前保存过的路径状态和属性 c.restore(); c.closePath(); //画分针 c.beginPath(); //保存当前环境的状态 c.save(); //顺时针旋转当前分针指向所形成的圆弧路径 c.rotate(2*Math.PI/60*min+2*Math.PI/60/60*sec); c.strokeStyle = "springgreen"; c.lineWidth = 3; c.moveTo(-30,0); c.lineTo(70,0); c.stroke(); //返回之前保存过的路径状态和属性 c.restore(); c.closePath(); //画秒针 c.beginPath(); //保存当前环境的状态 c.save(); //顺时针旋转当前秒针指向所形成的圆弧路径 c.rotate(2*Math.PI/60*sec); c.strokeStyle = "red"; c.lineWidth = 2 ; c.moveTo(-40,0); c.lineTo(120,0); c.stroke(); //返回之前保存过的路径状态和属性 c.restore(); c.closePath(); c.restore(); } clock(); setInterval(clock,1000);
相关推荐
nercon 2020-03-06
zsh 2020-03-01
wusiye 2020-10-23
表格的现在还是较为常用的一种标签,但不是用来布局,常见处理、显示表格式数据。在HTML网页中,要想创建表格,就需要使用表格相关的标签。<table> <tr> <td>单元格内的文字</td> ...
gufudhn 2020-08-09
nercon 2020-08-01
swiftwwj 2020-07-21
nercon 2020-07-16
饮马天涯 2020-07-05
Lophole 2020-06-28
gufudhn 2020-06-12
csstpeixun 2020-06-11
huzijia 2020-06-09
WebVincent 2020-06-06
行吟阁 2020-05-30
qsdnet我想学编程 2020-05-26
gufudhn 2020-05-25
qsdnet我想学编程 2020-05-19
suixinsuoyu 2020-05-15