canvas实现钟表

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#clock{
background: aqua;
}
</style>
</head>
<body>
<canvas id="clock" width="500" height="500"></canvas>
<script src="main.js"></script>
</body>
</html>
 /**
* Created by Administrator on 2016/10/14.
*/
(function () { var clock = document.querySelector("#clock");
var con = clock.getContext("2d"); //清理画布
function clearCanvas() {
con.clearRect(0, 0, 500, 500);
} // 绘制表盘
function drawClockDial() {
con.save();
con.beginPath();
con.fillStyle = "coral";
con.arc(250, 250, 200, 0, 2 * Math.PI);
con.fill();
var grad = con.createLinearGradient(0, 0, 0, 140);
grad.addColorStop(1, 'rgb(192, 80, 77)');
grad.addColorStop(0.5, 'rgb(155, 187, 89)');
grad.addColorStop(0, 'rgb(128, 100, 162)');
con.lineWidth = 6;
con.strokeStyle = grad;
con.stroke();
con.closePath();
con.restore(); for (var i = 0; i < 12; i++) { var x = 180 * Math.sin(i * 30 * Math.PI / 180);
var y = 180 * -Math.cos(i * 30 * Math.PI / 180);
con.save();
con.translate(240, 270);
con.font = "50px 宋体";
con.fillText(i.toString(), x, y);
con.restore(); }
} //绘制针
function drawHand() {
clearCanvas();
drawClockDial(); var time = new Date();
var hour = parseInt(time.getHours());
var min = parseInt(time.getMinutes());
var sec = parseInt(time.getSeconds()); //时针
con.save();
con.lineWidth = 5;
con.strokeStyle = "green";
con.translate(250, 250);
con.rotate((hour * 30 + min / 60) * Math.PI / 180);
con.beginPath();
con.moveTo(0, -100);
con.lineTo(0, 0);
con.lineCap = "round";
con.stroke();
con.closePath();
con.restore(); // 分针
con.save();
con.lineWidth = 5;
con.strokeStyle = "blue";
con.translate(250, 250);
con.rotate((min * 6 + sec / 60) * Math.PI / 180);
con.beginPath();
con.moveTo(0, -130);
con.lineTo(0, 0);
con.lineCap = "round";
con.stroke();
con.closePath();
con.restore(); //秒针
con.save();
con.lineWidth = 5;
con.strokeStyle = "red";
con.translate(250, 250);
con.rotate(sec * 6 * Math.PI / 180);
con.beginPath();
con.moveTo(0, -150);
con.lineTo(0, 0);
con.lineCap = "round";
con.stroke();
con.closePath();
con.restore(); //表心
con.save();
con.beginPath();
con.arc(250, 250, 5, 0, 2 * Math.PI);
con.closePath();
con.lineWidth = 3;
con.stroke();
con.restore(); requestAnimationFrame(drawHand);
} function init() {
drawHand();
} init();
})();

效果图:

canvas实现钟表

上一篇:css hr 设置


下一篇:Javascript 将一个句子中的单词首字母转成大写