您好,欢迎访问一九零五行业门户网

JavaScript html5 canvas绘制时钟效果_javascript技巧

本文实例讲述了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 < 60; i++) { context.rotate(rotate); context.moveto(0, start); context.lineto(0, end); } context.closepath(); context.stroke(); context.restore();}//绘画时分秒针方法function drawneedle(context, x, y, r, rotate, line){ context.save(); context.translate(x/2,y/2); context.beginpath(); context.rotate(rotate); context.moveto(0, 0.1*r); context.lineto(0, line); context.closepath(); context.stroke(); context.restore();}
希望本文所述对大家javascript程序设计有所帮助。
其它类似信息

推荐信息