<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas绘制表盘</title>
</head>
<body>
<canvas id='box' width="500" height="500" >
您的浏览器不支持canvas
</canvas>
<script>
var box = document.getElementById('box');
var ctx = box.getContext('2d');
// 时钟动起来
var timer = null;
function clock(){
var date = new Date();
var h = date.getHours();
h = h + h/60;
h = h>12? h-12:h;
var m = date.getMinutes();
var s = date.getSeconds();
// 清画布
ctx.clearRect(0,0,500,500);
// 画表盘
ctx.strokeStyle = '#f0f'; //空心填充颜色
ctx.lineWidth = 6; //笔触宽度
ctx.beginPath();
ctx.arc(250,250,200,0,2*Math.PI,false);
ctx.stroke();
ctx.closePath();
// 画时钟刻度(12个大格,每一个大格30度)
for(var i=0; i<12; i++){
ctx.save();
ctx.translate(250,250); //改变坐标系
ctx.rotate(30*i*Math.PI/180);
ctx.lineWidth = 3;
ctx.beginPath();
ctx.moveTo(0,-180);
ctx.lineTo(0,-192);
ctx.stroke();
ctx.restore();
}
//画分钟刻度(60个小格,每一个小格6度)
for(var i=0; i<60; i++){
ctx.save();
ctx.translate(250,250);
ctx.rotate(6*i*Math.PI/180);
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(0,-186);
ctx.lineTo(0,-192);
ctx.stroke();
ctx.restore();
}
// 画时针
ctx.save();
ctx.lineWidth = 5;
ctx.translate(250,250);
ctx.rotate(h*30*Math.PI/180);
ctx.beginPath();
ctx.moveTo(0,6);
ctx.lineTo(0,-80);
ctx.stroke();
ctx.restore();
// 画分针
ctx.save();
ctx.lineWidth = 3;
ctx.translate(250,250);
ctx.rotate(m*6*Math.PI/180);
ctx.beginPath();
ctx.moveTo(0,8);
ctx.lineTo(0,-100);
ctx.stroke();
ctx.restore();
// 画秒针
ctx.save();
ctx.lineWidth = 1;
ctx.translate(250,250);
ctx.rotate(s*6*Math.PI/180);
ctx.beginPath();
ctx.moveTo(0,10);
ctx.lineTo(0,-95);
ctx.stroke();
ctx.restore();
// 画中心的小圆固定三根针
ctx.save();
ctx.beginPath();
ctx.fillStyle = '#0f0';
ctx.lineWidth = 2;
ctx.translate(250,250);
ctx.arc(0,0,2,0,360,false);
ctx.stroke();
ctx.fill();
ctx.restore();
// 画秒针上的园
ctx.save();
ctx.fillStyle = '#f00';
ctx.lineWidth = 2;
ctx.translate(250,250);
ctx.rotate(s*6*Math.PI/180);
ctx.beginPath();
ctx.arc(0,-60,2,0,360,false);
ctx.stroke();
ctx.fill();
ctx.restore();
}
clock();
timer = setInterval(clock,1000);
</script>
</body>
</html>
canvas绘制时钟
最新推荐文章于 2022-02-09 18:04:31 发布
2400

被折叠的 条评论
为什么被折叠?



