
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>canvas</title>
<style>
body{background-color: rgba(0, 0, 0, 0.1)}
</style>
</head>
<body>
<canvas id="myCanvas" width="800" height="800" style="border:1px solid #d3d3d3;">
您的浏览器不支持 HTML5 canvas 标签。</canvas>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
$(function() {
var myAction = {},
ctx, earchSpeed = 60,
moonSpeed = 6;
var dom = {
earchSpeed: $('#m-earth-speed'),
moonSpeed: $('#m-moon-speed'),
btn: $('#m-btn'),
canvas: $('#myCanvas')
};
$.extend(myAction, {
initCanvas: function() {
ctx = dom.canvas[0].getContext("2d");
myAction.draw(ctx);
},
draw: function(ctx) {
requestAnimationFrame(function step() {
myAction.drawDial(ctx);
myAction.drawAllHands(ctx);
requestAnimationFrame(step);
});
},
drawAllHands: function(ctx) {
var time = new Date();
var s = time.getSeconds();
var m = time.getMinutes();
var h = time.getHours();
var pi = Math.PI;
var secondAngle = pi / 180 * 6 * s;
var minuteAngle = pi / 180 * 6 * m + secondAngle / 60;
var hourAngle = pi / 180 * 30 * h + minuteAngle / 12;
myAction.drawHand(hourAngle, 60, 6, "red", ctx);
myAction.drawHand(minuteAngle, 106, 4, "green", ctx);
myAction.drawHand(secondAngle, 129, 2, "blue", ctx);
},
drawHand: function(angle, len, width, color, ctx) {
ctx.save();
ctx.translate(150, 150);
ctx.rotate(-Math.PI / 2 + angle);
ctx.beginPath();
ctx.moveTo(-4, 0);
ctx.lineTo(len, 0);
ctx.lineWidth = width;
ctx.strokeStyle = color;
ctx.lineCap = "round";
ctx.stroke();
ctx.closePath();
ctx.restore();
},
drawDial: function() {
var pi = Math.PI;
ctx.clearRect(0, 0, 300, 300);
ctx.save();
ctx.translate(150, 150);
ctx.beginPath();
ctx.arc(0, 0, 148, 0, 2 * pi);
ctx.stroke();
ctx.closePath();
for (var i = 0; i < 60; i++) {
ctx.save();
ctx.rotate(-pi / 2 + i * pi / 30);
ctx.beginPath();
ctx.moveTo(110, 0);
ctx.lineTo(140, 0);
ctx.lineWidth = i % 5 ? 2 : 4;
ctx.strokeStyle = i % 5 ? "blue" : "red";
ctx.stroke();
ctx.closePath();
ctx.restore();
}
ctx.restore();
}
});
var init = function() {
myAction.initCanvas();
}();
})
</script>
</body>
</html>