本文主要是介绍用html5-canvas画可以走动的时钟,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
本文转自:http://www.w3cfuns.com/notes/19057/93ad0f7bf3f19cc78c67016cd1567395.html
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head><body><canvas width="1000" height="1000" id="clock">您的浏览器版本太低,不支持显示时钟的canvas标签</canvas><script>var clockID = document.getElementById("clock");var clock = clockID.getContext("2d");//画时钟的方法function drawClock(id){//每次清空画布clock.clearRect(0,0,1000,1000);//获取系统当前时间(时 、分 、秒)var now = new Date();var sec = now.getSeconds();sec = sec<10?"0"+sec:sec;var mins = now.getMinutes();mins = mins<10?"0"+mins:mins;var hours = now.getHours();hours = hours<10?"0"+hours:hours;//绘制文字,显示系统当前时间clock.save();clock.translate(0,500);clock.fillStyle = "#000"; clock.strokeStyle = "#fff";clock.font = "24px 微软雅黑";clock.strokeText("系统当前时间为:" + hours + "时" + mins + "分" + sec + "秒", 100, 100);clock.fillText("系统当前时间为:" + hours + "时" + mins + "分" + sec + "秒", 100, 100);clock.restore();//计算:满60分加一小时hours = hours + mins / 60;//计算:将24小时制转化为12小时制hours = hours>12?hours-12:hours;//画表盘clock.beginPath();clock.lineWidth = 10;clock.strokeStyle = "#000";clock.arc(300,300,200,0,360,false);clock.stroke();clock.closePath();//画刻度盘//时刻度for(var i=0;i<12;i++){clock.save();//将起始点定位到圆心 clock.translate(300,300);//设置刻度的样式clock.lineWidth = 7;clock.strokeStyle = "#000";//设置旋转角度clock.rotate(i * 30 * Math.PI / 180);clock.beginPath();clock.moveTo(0, -170);clock.lineTo(0, -190);clock.stroke();clock.restore(); };//分刻度for (var j = 0; j < 60; j++){clock.save();clock.translate(300, 300);clock.lineWidth = 3;clock.strokeStyle = "#000";clock.rotate(j * 6 * Math.PI / 180);clock.beginPath();clock.moveTo(0, -180);clock.lineTo(0, -190);clock.closePath();clock.stroke();clock.restore();};//时针clock.save();clock.translate(300, 300);clock.lineWidth = 7;clock.strokeStyle = "#000000";//设置小时的旋转角度,每转一次走30°clock.rotate(hours * 30 * Math.PI / 180);clock.beginPath();clock.moveTo(0, 15);clock.lineTo(0, -120);clock.stroke();clock.closePath();clock.restore();//分针clock.save();clock.translate(300, 300);clock.rotate(mins * 6 * Math.PI / 180);clock.lineWidth = 5;clock.strokeStyle = "#000";clock.beginPath();clock.moveTo(0, 20);clock.lineTo(0, -160);clock.stroke();clock.closePath();clock.restore();//秒针clock.save();clock.translate(300, 300);clock.rotate(sec * 6 * Math.PI / 180);clock.lineWidth = 3;clock.strokeStyle = "#f00";clock.beginPath();clock.moveTo(0, 25);clock.lineTo(0, -165);clock.stroke();clock.closePath();//秒针圆心处一个小圈clock.fillStyle = "#fff";clock.strokeStyle = "#f00";clock.beginPath();clock.arc(0, 0, 6, 0, 360, false);clock.fill();clock.stroke();clock.closePath();//秒针顶部一个小圈clock.beginPath();clock.arc(0, -140, 3, 0, 360, false);clock.fillStyle = "#f00";clock.stroke();clock.closePath();clock.restore();}drawClock();setInterval(drawClock, 1000); //使表针根据系统当前时间转动起来</script>
</body>
</html>
效果如下:
这篇关于用html5-canvas画可以走动的时钟的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!