canvas实现动态时钟
<canvas id="can" width="500" height="500" style="background-color: pink;">
</canvas>
</body>
<script>
function showTime(){
var now = new Date();
var hours = now.getHours();
var mins = now.getMinutes();
var secs = now.getSeconds();
hours = hours + mins/60;
// 获取画布
var canvas = document.getElementById("can")
// 获取画笔
var g = can.getContext("2d");
//清理画布
g.clearRect(0, 0, canvas.width, canvas.height);
// 开启路径
g.beginPath();
g.strokeStyle = "white";
g.lineWidth =2;
g.arc(250, 250, 250, 0, Math.PI * 2, true)
g.stroke();
g.closePath();
//表盘
for(var i=0; i<12;i++){
g.save();
g.translate(250,250);
g.beginPath();
g.rotate(i*30*Math.PI/180)
g.strokeStyle="red";
g.lineWidth=5;
g.moveTo(0,-225);
g.lineTo(0,-205);
g.stroke();
g.closePath();
g.restore();
}
//时针
g.save();
g.translate(250,250);
g.beginPath();
g.rotate(hours*30*Math.PI/180);
g.strokeStyle="red";
g.lineWidth=7;
g.moveTo(0,-50);
g.lineTo(0,-0);
g.stroke();
g.closePath();
g.restore();
//分针
g.save();
g.translate(250,250);
g.beginPath();
g.rotate(mins*6*Math.PI/180);
g.strokeStyle="red";
g.lineWidth=5;
g.moveTo(0,-100);
g.lineTo(0,0);
g.stroke();
g.closePath();
g.restore();
//秒针
g.save();
g.translate(250,250);
g.beginPath();
g.rotate(secs*6*Math.PI/180);
g.strokeStyle="red";
g.lineWidth=3;
g.moveTo(0,-160);
g.lineTo(0,10);
g.stroke();
g.closePath();
g.restore();
}
//每秒执行一次
setInterval(showTime,1000);
//先执行一次,消除延迟
showTime();
</script>
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容