html5 --- 时钟
实际代码如下: <html> <head></head> <body> <canvas id="my_html5" width="400" height="400" style="border:1px solid black;"></canvas> <script type="text/javascript"> var ctx = document.getElementById('my_html5').getContext('2d'), img = new Image(); img.src = "caishen_001.gif"; //当图片载入后执行方法 img.onload = function(){ //ctx.drawImage(img,0,0); init(); }; function init(){ clock(); //ctx.clearRect(0,0,400,400); setInterval(clock,1000); }; function clock(){ var date = new Date(); //设置画笔画线颜色 ctx.strokeStyle = 'black'; //清空画布 ctx.clearRect(0,0,400,400); //保存画布状态 ctx.save(); //将中心点重置为200,200 ctx.translate(200,200); //画图[p1、图片对象 p2、坐标x p3、坐标y p4、图标宽 p5、图片高] ctx.drawImage(img,-100,-100,200,200); //缩放为宽0.8 高0.8 ctx.scale(0.8,0.8); //时刻度 //边宽度 ctx.lineWidth = 7; for(var i = 12; i > 0; i--){ //开始路径 ctx.beginPath(); //翻转[以中心200,200翻转参数度数] ctx.rotate(Math.PI/6) //将画笔移动到p1,p2位置 ctx.moveTo(210,0);; //从画笔的位置到当前lineTo的位置 以直线连接 ctx.lineTo(230,0); ctx.stroke(); } //分刻度 ctx.lineWidth = 3; for (var i = 60; i > 0; i--){ ctx.beginPath(); ctx.moveTo(220,0); ctx.lineTo(230,0); ctx.rotate(Math.PI/30); ctx.stroke(); } //外圈 ctx.lineWidth = 7; ctx.strokeStyle = "blue"; ctx.beginPath(); ctx.moveTo(240,0); //画圆 【p1、x p2、y p3、半径 p4、起始位置弧度 p5、结束弧度 p6、是否顺时针】 ctx.arc(0,0,240,0,Math.PI*2,true); ctx.stroke(); var h = date.getHours(), m = date.getMinutes(), s = date.getSeconds(); h = Math.PI / 6 * h + Math.PI / 6 / 60 * m; m = Math.PI / 30 * m - h; s = Math.PI / 30 * s - m - h; ctx.rotate(Math.PI / 2 * 3); //时针 ctx.beginPath(); ctx.lineWidth = 12; ctx.strokeStyle = 'black'; ctx.rotate(h); ctx.moveTo(-20,0); ctx.lineTo(100,0); ctx.stroke(); ctx.fillStyle = 'black'; ctx.arc(100,0,6,0,Math.PI*2,true); ctx.arc(-30,0,6,0,Math.PI*2,true); ctx.fill(); //分针 ctx.beginPath(); ctx.lineWidth = 8; ctx.rotate(m); ctx.moveTo(-30,0); ctx.lineTo(160,0); ctx.stroke(); //秒针 ctx.lineWidth = 4; ctx.strokeStyle = 'red'; ctx.beginPath(); ctx.rotate(s); ctx.moveTo(-50,0); ctx.lineTo(-5,0); ctx.moveTo(5,0); ctx.arc(0,0,5,0,Math.PI*2,true); ctx.lineTo(190,0); ctx.stroke(); ctx.restore(); }; </script> </body> </html> |