<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>钟表</title>
<style>
canvas{
position:absolute;
left:10;
top:10;
}
</style>
</head>
<body>
<canvas id="dial_canvas">表盘</canvas>
<canvas id="hand_canvas">指针</canvas>
<script>
//定义变量
var w = 600, h = 600; //画布的宽高
var x = 300, y = 300; //圆心坐标
var r = 200; //半径
//获取 canvas元素
var dial_canvas = document.querySelector("#dial_canvas");
dial_canvas.width = w;
dial_canvas.height = h;
var hand_canvas = document.querySelector("#hand_canvas");
hand_canvas.width = w;
hand_canvas.height = h;
//获取绘图环境
var dial_cxt = dial_canvas.getContext("2d");
var hand_cxt = hand_canvas.getContext("2d");
//绘制表盘
dial_cxt.arc(x, y, r, 0, Math.PI * 2);
dial_cxt.strokeStyle = "#000";
dial_cxt.lineWidth = 10;
dial_cxt.stroke();
//绘制 小时 刻度
drawScale(dial_cxt, x, y, r, r-20, 12, "#000", 10);
//绘制 分钟刻度
drawScale(dial_cxt, x, y, r, r-10, 60, "#000", 4);
//绘制指针
function runTime(){
hand_cxt.clearRect(0,0,w,h); //清空画布
//hand_canvas.width = hand_canvas.width;
//获取当前时间
var date = new Date();
//绘制秒针
var s = date.getSeconds();
drawHand(hand_cxt, x, y, s / 60 * 360, 180, 2, "red");
//绘制分针
var m = date.getMinutes() + s / 60;
drawHand(hand_cxt, x, y, m / 60 * 360, 150, 5, "#000");
//绘制时针
var hour = date.getHours() % 12 + m / 60;
drawHand(hand_cxt, x, y, hour / 12 * 360, 120, 8, "#000")
setTimeout(runTime, 1000);
}
runTime();
/**
* 绘制指针
* object cxt 绘图环境
* number x 圆心x坐标
* number y 圆心y坐标
* number angle 偏移的角度
* number handLength 指针的长度
* number handWidth 指针的宽度
* string handColor 指针的颜色
*/
function drawHand(cxt, x, y, angle, handLength, handWidth = 10, handColor = "#000"){
cxt.save();
cxt.translate(x, y);
cxt.rotate((angle - 90) / 180 * Math.PI);
cxt.beginPath();
cxt.moveTo(-20, 0);
cxt.lineTo(handLength, 0);
cxt.strokeStyle = handColor;
cxt.lineWidth = handWidth;
cxt.stroke();
cxt.restore();
}
/**
* 绘制刻度
* object cxt 绘图环境
* nubmer x 圆心x坐标
* nubmer y 圆心y坐标
* number outerRadius 外圆半径
* number innerRadius 内圆半径
* number num 刻度的数量
* number strokeStyle 刻度的颜色 默认值 #000
* number strokeWidth 刻度的宽度 默认值 10
*/
function drawScale(cxt, x, y, outerRadius, innerRadius, num, strokeStyle = "#000", strokeWidth = 10) {
//计算 间隔的角度(弧度)
var angle = Math.PI * 2 / num;
//相关设置
cxt.beginPath(); //开启路径
cxt.strokeStyle = strokeStyle;
cxt.lineWidth = strokeWidth;
//循环绘制
for (var i = 0; i < num; i ++) {
var x1 = Math.cos(angle * i) * outerRadius + x;
var y1 = Math.sin(angle * i) * outerRadius + y;
var x2 = Math.cos(angle * i) * innerRadius + x;
var y2 = Math.sin(angle * i) * innerRadius + y;
cxt.moveTo(x1, y1);
cxt.lineTo(x2, y2);
}
cxt.stroke(); //进行绘制
}
</script>
</body>
</html>
转载于:https://my.oschina.net/u/3502339/blog/1069072