历史版本1 :JS实现时钟效果 返回文档
编辑时间: 内容长度:图片数:目录数: 修改原因:

目录:

1.问题描述:编辑

在做报表的时候希望实时的展现时间,并有一个比较美观的效果,如下图:


222

2.实现思路编辑

利用HTIML5的画布功能并配合js代码,获取系统的实时时间,并间隔一秒绘制一次时钟。

3.实现步骤编辑

在单元格中输入以下代码,然后使用HTML显示内容:

<canvas id="view" height="300px" width="300px"></canvas> 

222

代码中的宽和高属性可以根据自己的需要调整。

然后在预览方式中添加js加载结束事件:

222

代码如下:

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);

保存预览即可。

4.备注编辑

如果是在表单中,就添加报表块然后执行相同操作,然后在报表块的事件里把上述js代码添加到下面代码的function里面。

setTimeout(function(){ },1000);