<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#mycanvas{
position: absolute;
left: 50%;
margin-left: -250px;
border: 5px solid #fff;
box-shadow: 0 0 10px rgba(0,0,0,.2);
background-color: rgb(58,179,255);
}
</style>
</head>
<body>
<!--canvas:html5画布对象,可以在其中绘制任何图形,以及线条效果
注意:canvas的尺寸应该通过元素的属性直接设置,而不是使用样式实现(失帧)
-->
<canvas id="mycanvas" width="500px" height="500px">
</canvas>
<script type="text/javascript">
//获取画布对象
var mycanvas = document.getElementById("mycanvas");
//获取一个2D绘图环境(拿到一只画笔)
var ctx = mycanvas.getContext('2d')
function draw(){
//获取系统时间
var nowTime = new Date();
var hours = nowTime.getHours(); //获取时
var minutes = nowTime.getMinutes(); //获取分
var seconds = nowTime.getSeconds(); //获取秒
hours = hours > 12 ? hours - 12 : hours;
hours = hours + minutes/60;
//清除画布(防止覆盖)
ctx.clearRect(0,0,500,500);
//初始化画笔样式
ctx.lineWidth = 5;
ctx.strokeStyle = '#fff';
ctx.beginPath();
// 设置一个圆形路径
ctx.arc(250, 250, 150, 0 , 360, false);//圆心 半径 起始结束度数 顺时针
//绘制圆形
ctx.stroke();
ctx.closePath();
//绘制刻度(时刻度)
for(var i = 0;i < 12; i++){
//保存当前绘图环境
ctx.save();
//重置绘图起始位置(将圆心位置重置为0,0点)
ctx.translate(250,250);
//旋转画布到一定弧度 弧度=角度*PI/180
ctx.rotate(i * 30 * Math.PI / 180);
//设置绘图线条的起始位置
ctx.moveTo(0,140);
//设置绘图线条的结束位置
ctx.lineTo(0,150);
//绘制路径
ctx.stroke();
//还原初始的绘图环境
ctx.restore();
ctx.closePath();
}
//绘制刻度(分刻度)
ctx.lineWidth = 3;
for(var i = 0;i < 60; i++){
ctx.beginPath();
//保存当前绘图环境
ctx.save();
//重置绘图起始位置(将圆心位置重置为0,0点)
ctx.translate(250,250);
//旋转画布到一定弧度 弧度=角度*PI/180
ctx.rotate(i * 6 * Math.PI / 180);
//设置绘图线条的起始位置
ctx.moveTo(0,143);
//设置绘图线条的结束位置
ctx.lineTo(0,150);
//绘制路径
ctx.stroke();
//还原初始的绘图环境
ctx.restore();
ctx.closePath();
}
//绘制时针
ctx.beginPath();
ctx.lineWidth = 5;
//保存当前绘图环境
ctx.save();
//重置绘制起始位置(将圆心位置重置为0,0)
ctx.translate(250,250)
//将画布旋转到一定弧度
ctx.rotate((hours * 30+180) * Math.PI / 180);
//设置线条的起始位置
ctx.moveTo(0, -10);
//设置线条的结束位置
ctx.lineTo(0, 100);
//绘制路径
ctx.stroke();
//还原初始的绘图环境
ctx.restore();
ctx.closePath();
//绘制分针
ctx.beginPath();
ctx.lineWidth = 3;
//保存当前绘图环境
ctx.save();
//重置绘制起始位置(将圆心位置重置为0,0)
ctx.translate(250,250)
//将画布旋转到一定弧度
ctx.rotate((minutes * 6 +180) * Math.PI / 180);
//设置线条的起始位置
ctx.moveTo(0, -10);
//设置线条的结束位置
ctx.lineTo(0, 120);
//绘制路径
ctx.stroke();
//还原初始的绘图环境
ctx.restore();
ctx.closePath();
//绘制秒钟
ctx.beginPath();
ctx.lineWidth = 1;
ctx.strokeStyle = "#f00";
//保存当前绘图环境
ctx.save();
//重置绘制起始位置(将圆心位置重置为0,0)
ctx.translate(250,250)
//将画布旋转到一定弧度
ctx.rotate((seconds * 6+180) * Math.PI / 180);
//设置线条的起始位置
ctx.moveTo(0, -10);
//设置线条的结束位置
ctx.lineTo(0, 135);
//绘制路径
ctx.stroke();
//还原初始的绘图环境
ctx.restore();
ctx.closePath();
}
window.setInterval(draw,1000);
</script>
</body>
</html>
H5 画布时钟
最新推荐文章于 2022-08-27 13:36:56 发布