JavaScript html5 canvas绘制时钟效果_javascript技巧
程序员文章站
2022-03-11 21:21:48
...
本文实例讲述了JavaScript+html5 canvas绘制时钟效果。分享给大家供大家参考,具体如下:
HTML部分:
canvas绘图
JavaScript部分:
function init(){ var canvas = document.getElementById("canvas"), context = canvas.getContext("2d"); 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, 0, x, y); //清除绘画历史 //绘画钟框 context.fillStyle = "#f1f1f1"; drawCircle(context, x, y, r); //绘画文字 var tx = x/2,ty = y/2,tr = 0.8*r; context.font = "bold 12px 微软雅黑"; context.fillStyle = "#000"; drawText(context, "1", tx + 0.5*tr,ty - 0.866*tr); drawText(context, "2", tx + 0.866*tr, ty - 0.5*tr); drawText(context, "3", tx + tr, ty); drawText(context, "4", tx + 0.866*tr, ty + 0.5*tr); drawText(context, "5", tx + 0.5*tr, ty + 0.866*tr); drawText(context, "6", tx, ty + tr); drawText(context, "7", tx - 0.5*tr, ty + 0.866*tr); drawText(context, "8", tx - 0.866*tr, ty + 0.5*tr); drawText(context, "9", tx - tr, ty); drawText(context, "10", tx - 0.866*tr, ty - 0.5*tr); drawText(context, "11", tx - 0.5*tr, ty - 0.866*tr); drawText(context, "12", tx, 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, x, y, r, angleH, -0.88*r, -0.96*r, 3); //绘制分刻度 drawScale(context, x, y, r, angleM, -0.93*r, -0.96*r, 1); //绘画时分秒针 drawCircle(context, x, y, 3); drawNeedle(context, x, y, r, h*angleH + m*angleM/12, -0.5*r); drawNeedle(context, x, y, r, m*angleM + s*angleM/60, -0.6*r); drawNeedle(context, x, y, r, s*angleM, -0.75*r); } //绘画圆 function drawCircle(context, x, y, r){ context.save(); context.beginPath(); context.arc(x/2, y/2, r, 0, Math.PI*2, 0); context.fill(); context.closePath(); context.restore(); } //绘画文字方法 function drawText(context, text, x, y){ context.save(); x -= (context.measureText(text).width/2); y += 4; context.translate(x, y); context.fillText(text, 0, 0); context.restore(); } //绘制刻度方法 function drawScale(context, x, y, r, rotate, start, end, lineWidth){ context.save(); context.beginPath(); context.translate(x/2,y/2); context.lineWidth = lineWidth; for (var i = 0; i
希望本文所述对大家JavaScript程序设计有所帮助。
推荐阅读
-
使用javascript和HTML5 Canvas画的四渐变色播放按钮效果
-
javascript+HTML5 canvas绘制时钟功能示例
-
使用javascript和HTML5 Canvas画的四渐变色播放按钮效果
-
JavaScript Canvas绘制圆形时钟效果
-
javascript+HTML5 canvas绘制时钟功能示例
-
JavaScript canvas实现七彩时钟效果
-
纯JavaScript实现HTML5 Canvas六种特效滤镜示例_javascript技巧
-
JavaScript html5 canvas绘制时钟效果
-
js+html5实现canvas绘制圆形图案的方法_javascript技巧
-
js实现Form栏显示全格式时间时钟效果代码_javascript技巧