直接运行即可:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<canvas id="myCanvas" width="200" height="200" style="border:1px solid #c3c3c3;">
</canvas>
<span id="mySpan"></span>
<script>
//getMX表示根据度数和指针的半径获得x的相对坐标
function getMX(deg, r) {
var tan = Math.abs(Math.tan(deg * Math.PI / 180));
return r * tan / Math.sqrt((1 + tan * tan));
}
function getY(x, r) {
return Math.sqrt(r * r - x * x)
}
//getRealX就是获得绝对坐标
function getRealX(dgree, x) {
if (dgree <= 180) {
return R + x;
} else {
return R - x;
}
}
function getRealY(dgree, y) {
if (dgree < 90 || dgree > 270) {
return R - y;
} else {
return R + y;
}
}
function drawText() {
ctx.strokeText("12", 100, 15);
ctx.strokeText("3", 185, 100);
ctx.strokeText("6", 100, 185);
ctx.strokeText("9", 15, 100);
ctx.textAlign="center";
ctx.font="20px sans-serif ";
}
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var R = 100;
//ctx.fillStyle = "#FF0000";
// ctx.fillRect(0, 0, 150, 75);
function draw() {
ctx.clearRect(0, 0, 200, 200);
// 获取当前时间
var date = new Date();
var mr = 70;
var hr = 50;
var sr = 90;
// 分针对应的度数
var mDgree = date.getMinutes() * 6;
// mx 分针对应的X轴的坐标
var mx = getMX(mDgree, mr);
// my 分针对应的Y轴的坐标
var my = getY(mx, mr);
var hDgree = date.getHours() * 30 + date.getMinutes() / 60 * 30;
// hx 时针对应的X轴的坐标
var hx = getMX(hDgree, hr);
// hy 时针对应的Y轴的坐标
var hy = getY(hx, hr);
var sDgree = date.getSeconds() * 6;
// sx 秒针对应的X轴的坐标
var sx = getMX(sDgree, sr);
// sy 秒针对应的Y轴的坐标
var sy = getY(sx, sr);
mx = getRealX(mDgree, mx);
my = getRealY(mDgree, my);
hx = getRealX(hDgree, hx);
hy = getRealY(hDgree, hy);
sx = getRealX(sDgree, sx);
sy = getRealY(sDgree, sy);
ctx.beginPath();
ctx.arc(R, R, R, 0, 2 * Math.PI);
ctx.stroke();
ctx.moveTo(R, R);
ctx.lineTo(mx, my);
ctx.stroke();
ctx.moveTo(R, R);
ctx.lineTo(hx, hy);
ctx.stroke();
ctx.moveTo(R, R);
ctx.lineTo(sx, sy);
ctx.stroke();
drawText();
document.getElementById('mySpan').innerHTML = "seconds:" + date.getSeconds() + ", degree:"
+ sDgree + ", sx:" + sx + ",sy:" + sy;
}
//draw();
setInterval(draw, 1000);
</script>
</body>
</html>
网友评论