How to realize a simple clock through Canvas+JS
Today, I will talk to you about how to achieve a simple clock through Canvas+JS. Many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.
I learned the canvas element in html5 before, and I realized a simple clock in order to practice my hands. The clock itself is not complicated, nor does it use pictures to beautify it, but although the sparrow has all the organs, let's share it with you:
Achieve results:
Html Code:
Clock * {margin: 0; padding: 0;} .canvas {margin-left: 20px; margin-top: 20px; border: solid 1px;}
JS Code:
Var Canvas = {}; Canvas.cxt = document.getElementById ('canvasId'). GetContext (' 2d'); Canvas.Point = function (x, y) {this.x = x; this.y = y;}; / * erase all graphics on canvas * / Canvas.clearCxt = function () {var me = this; var canvas = me.cxt.canvas; me.cxt.clearRect (0L0, canvas.offsetWidth, canvas.offsetHeight);} / * clock * / Canvas.Clock = function () {var me = Canvas, c = me.cxt, radius = 150, / * Radius * / scale = 20, / * scale length * / minangle = (1x30) * Math.PI, / * Radian of one minute * / hourangle = (1lap 6) * Math.PI, / * Radian of one hour * / hourHandLength = radius/2 / * length of hour hand * / minHandLength = radius/3*2, / * length of minute hand * / secHandLength = radius/10*9, / * length of second hand * / center = new me.Point (c.canvas.width/2, c.canvas.height/2) / * draw center (dial center) * / function drawCenter () {c.save (); c.translate (center.x, center.y); c.fillStyle = 'black'; c.beginPath (); c.arc (0,0, radius/20, 0, 2*Math.PI); c.closePath (); c.fill () C.stroke (); c.restore ();}; / * draw dial by coordinate transformation * / function drawBackGround () {c.save (); c.translate (center.x, center.y); / * Translational transformation * / * draw scale * / function drawScale () {c.moveTo (radius-scale, 0) C.lineTo (radius, 0);}; c.beginPath (); c.arc (0,0, radius, 0, 2*Math.PI, true); c.closePath (); for (var I = 1; I