使用js实现时钟效果
生活随笔
收集整理的這篇文章主要介紹了
使用js实现时钟效果
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
首先在單元格中輸入下面的代碼,然后使用html顯示內容。
<canvas id="view" height="300px" width="300px"></canvas> 這個寬高可以根據自己需要填。
然后在預覽方式中添加加載結束事件:
var dom=document.getElementById("view"); var ctx=dom.getContext("2d"); var width=ctx.canvas.width; var height=ctx.canvas.height; var r=width/2;function drawBackground(){ctx.translate(r,r);ctx.beginPath();ctx.lineWidth=10;ctx.arc(0,0,r-5,0,2*Math.PI);ctx.stroke();for(var i=0;i<60;i++){var x=(r-20)*Math.cos(Math.PI*2/60*i);var y=(r-20)*Math.sin(Math.PI*2/60*i); if(i%5===0){ctx.fillStyle="#000000";}else{ctx.fillStyle="#cccccc";}ctx.beginPath();ctx.arc(x,y,5,0,2*Math.PI);ctx.fill();}ctx.font="20px Arial";ctx.textAlign="center";ctx.textBaseline="middle";ctx.fillStyle="#000000";for(var j=0;j<12;j++){var ax=(r-50)*Math.cos(Math.PI*2/12*j);var ay=(r-50)*Math.sin(Math.PI*2/12*j); ctx.beginPath();ctx.fillText(j>9?j-9:j+3,ax,ay);ctx.fill();} } function drawHour(hour,minute,second){ctx.save();ctx.beginPath();var rad=2*Math.PI/12*hour+2*Math.PI/12/60*minute+2*Math.PI/12/60/3600*second;ctx.rotate(rad);ctx.lineWidth=14;ctx.lineCap="round";ctx.moveTo(0,20);ctx.lineTo(0,-r+100);ctx.stroke();ctx.restore(); } function drawMinute(minute,second){ctx.save();ctx.beginPath();var rad=2*Math.PI/60*minute+2*Math.PI/3600*second;ctx.rotate(rad);ctx.lineWidth=10;ctx.lineCap="round";ctx.moveTo(0,20);ctx.lineTo(0,-r+80);ctx.stroke();ctx.restore(); } function drawSecond(second){ctx.save();ctx.beginPath();ctx.fillStyle="#FF0000";var rad=2*Math.PI/60*second;ctx.rotate(rad);ctx.lineWidth=2;ctx.lineCap="round";ctx.moveTo(0,30);ctx.lineTo(8,0);ctx.lineTo(0,-r+30);ctx.lineTo(-8,0);ctx.lineTo(0,30);ctx.fill();ctx.restore(); } function run(){ctx.clearRect(0,0,width,height);ctx.save();var time =new Date();var hour=time.getHours();var minute=time.getMinutes();var second=time.getSeconds();drawBackground();drawHour(hour,minute,second);drawMinute(minute,second);drawSecond(second);ctx.fillStyle="#555";ctx.beginPath();ctx.arc(0,0,8,0,2*Math.PI);ctx.fill();ctx.restore(); } window.setInterval(function(){run();},1000);
如果是在表單中,就添加報表塊然后執行相同操作,然后在報表塊的事件里把上述js代碼添加到下面代碼的function里面
setTimeout(function(){ },1000);
總結
以上是生活随笔為你收集整理的使用js实现时钟效果的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 韦恩图——帮助你更好地表达多个数据集合之
- 下一篇: SAP数据集