欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

html5 canvas绘制钟表

程序员文章站 2022-05-06 21:58:41
终于没有兼容bug了 。。。   [html]       <...

终于没有兼容bug了 。。。

 

[html]
<!doctype html> 
<html> 
<head> 
<meta charset="utf-8"> 
<title></title> 
<style type="text/css"> 
* { 
    margin: 0; 
    padding: 0; 

canvas { 
    box-shadow: 0 0 10px 10px #cccccc; 
    display: block; 
    margin: 50px auto 0; 

</style> 
<script type="text/javascript"> 
window.onload = function() { 
    new canvasclock({ 
        canvas: document.getelementbyid("canvas"), 
        r: 100, 
        h: [0, -30], 
        m: [0, -60], 
        s: [0, -90] 
    }) 
}; 
function canvasclock(opts) { 
    var self = this; 
    self.r = opts.r; 
    self.h = opts.h; 
    self.m = opts.m; 
    self.s = opts.s; 
    self.pi = math.pi; 
    self.canvas = opts.canvas; 
    self.context = self.canvas.getcontext("2d"); 
    window.setinterval(function() { 
        self.canvas.width = 0; 
        self.canvas.height = 0; 
        self.canvas.width = 400; 
        self.canvas.height = 400; 
        self.context.strokestyle = "rgba(255,0,0,0.1)"; 
        self.context.translate(self.r * 2, self.r * 2); 
        self.createtime("m"); 
        self.createtime("h"); 
        self.createtime("s") 
    }, 
    1000) 
}; 
canvasclock.prototype = { 
    createtime: function(str) { 
        var self = this; 
        var context = self.context; 
        context.linewidth = 1; 
        context.beginpath(); 
        context.arc(0, 0, self.r, 0, 2 * self.pi, true); 
        context.stroke(); 
        context.closepath(); 
        var s = (new date()).getseconds(); 
        var m = (new date()).getminutes(); 
        var h = (new date()).gethours(); 
        if (str == "s") { 
            var t = s * 6; 
            var x = self.s[0]; 
            var y = self.s[1] 
        } else if (str == "m") { 
            var t = (m + s / 60) * 6; 
            var x = self.m[0]; 
            var y = self.m[1] 
        } else { 
            var t = (h + m / 60) * 30; 
            var x = self.h[0]; 
            var y = self.h[1] 
        } 
        context.linewidth = 10; 
        context.linecap = "round"; 
        context.rotate(t * self.pi / 180); 
        context.beginpath(); 
        context.moveto(0, 0); 
        context.lineto(x, y); 
        context.stroke(); 
        context.closepath() 
    } 

</script> 
</head> 
 
<body> 
<canvas width="400" height="400" id="canvas"></canvas> 
</body> 
</html> 

 


摘自 事与愿违