<canvas id="skyCanvas" width="600" height="600" style="background: #000;"></canvas>
<script>
var canvas = document.querySelector("#skyCanvas");
var brush = canvas.getContext("2d");
// 绘制静态时钟
clock();
// 使用定时器让表针动起来
setInterval(clock, 1000);
function clock() {
// 去除拖影,使得每次渲染前清空画布
brush.clearRect(0, 0, 600, 600);
// 得到时分秒,Date对象
var date = new Date();
var hour = date.getHours();
var newHour = hour > 12 ? (hour - 12) : hour;// 返回24小时制,但是表只有12个指针,所以需要转换成12小时制
var minute = date.getMinutes();
var second = date.getSeconds();
// 绘制圆形表盘
brush.beginPath();
brush.arc(300, 300, 250, 0, Math.PI * 2, false);//false是顺时针,true是逆时针,但对于圆来讲,顺时针或逆时针来绘制都OK
brush.strokeStyle = "skyblue";
brush.lineWidth = "5";
brush.stroke();
brush.closePath();
// 绘制时针的刻度
brush.beginPath();
brush.lineWidth = "3";
brush.strokeStyle = "yellow";
// 循环实现时针的12个刻度
for (var i = 1; i <= 12; i++) {
brush.save();
brush.translate(300, 300);//改变圆心
brush.rotate(Math.PI / 180 * 30 * i);//每一次旋转30度
brush.moveTo(0, -245);//点在圆心上面
brush.lineTo(0, -230);
brush.stroke();
brush.restore();//画一个归零一个
}
brush.closePath();
// 分针刻度
// can.beginPath()
// for (var i = 1; i <= 60; i++) {
// can.save()
// // 改变圆心
// can.translate(300, 300)
// can.rotate(Math.PI / 180 * 6 * i)
// can.moveTo(0, -245)
// can.lineTo(0, -235)
// can.lineWidth = "3"
// can.strokeStyle = "red";
// can.stroke()
// can.restore()
// }
// can.closePath()
// 绘制时针
pointer(30, newHour, 0, 20, 0, -120, "5", "skyblue");
// 绘制分针
pointer(6, minute, 0, 20, 0, -160, "3", "pink");
// 绘制秒针
pointer(6, second, 0, 20, 0, -180, "1", "yellow");
// 绘制秒针上靠近圆心的圆形
pointerCircle(6, second, 0, 0, 10, "skyblue", "yellow");
// 绘制秒针上远离圆心的圆形
pointerCircle(6, second, 0, -146, 10, "skyblue", "yellow");
}
// 绘制时针、分针、秒针,还有转动的角度
function pointer(distance, time, mstart, mend, lstart, lend, linew, strokes) {
brush.beginPath();
brush.save();
brush.translate(300, 300);//改变圆心
brush.rotate(Math.PI / 180 * distance * time);//按获取的系统的小时走,走了几个小时,就重新绘制多少度的时针
brush.moveTo(mstart, mend);//因为指针的不是在圆心其起始,露出了一个小头
brush.lineTo(lstart, lend);
brush.lineWidth = linew;
brush.strokeStyle = strokes;
brush.stroke();
brush.restore();
brush.closePath();
}
// 绘制时针上的两个圆圈
function pointerCircle(distance, time, xstart, yend, radius, fills, strokes) {
brush.beginPath();
brush.save();
brush.translate(300, 300);
brush.rotate(Math.PI / 180 * distance * time);
brush.arc(xstart, yend, radius, 0, Math.PI * 2, true);//x,y,r,,角度....
brush.fillStyle = fills;
brush.strokeStyle = strokes;
brush.fill();
brush.stroke();
brush.restore();
brush.closePath();
}
</script>
canvas 绘制转动的钟表
最新推荐文章于 2024-07-02 22:34:09 发布