canvas-绘制时钟

时间:2023-03-09 18:35:24
canvas-绘制时钟

把最近学到的一些canvas技能全部发上来,刚开始写博客,感觉还不太习惯,不过我相信慢慢就会习惯了。不啰嗦了,把代码送上,看不懂的话可以先去学习下基础教程,把基础学好了也就能看懂了。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<canvas id="canvas" width="500" height="500">你的浏览器不支持canvas</canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d"); function clock(){
ctx.clearRect(0,0,canvas.width,canvas.height);
var date = new Date();
var s = date.getSeconds();
var m = date.getMinutes();
var h = date.getHours();
var r = canvas.width/2.5; //半径
ctx.save();
ctx.translate(250,250);//平移之后坐标系跟着变化
ctx.rotate(-Math.PI/2);//旋转之后坐标系跟着变化 ctx.save();// 记录旋转画布之前初始状态
ctx.lineWidth = 3;
ctx.strokeStyle = "#CCCCCC";
//分刻度
for(var i = 0;i < 60;i++ ){
ctx.beginPath();
ctx.rotate(Math.PI/30);
ctx.moveTo(165,0);
ctx.lineTo(180,0);
ctx.stroke();
}
ctx.restore();// 恢复初始状态,未旋转前 ctx.save();
ctx.lineWidth = 5;
ctx.strokeStyle="black";
//时刻度
for (var i = 0; i < 12; i++) {
ctx.beginPath();
ctx.rotate(Math.PI/6);// 旋转画布绘制刻度
ctx.moveTo(155,0);
ctx.lineTo(180,0);
ctx.stroke();
}
ctx.restore(); ctx.save();
//秒针
ctx.strokeStyle = "blue";
ctx.lineWidth = 2;
ctx.beginPath();
ctx.rotate(s*Math.PI/30);
ctx.moveTo(-40,0);
ctx.lineTo(170,0);
ctx.stroke(); ctx.restore(); ctx.save();
//分针
ctx.strokeStyle = "black";
ctx.lineWidth = 3;
ctx.beginPath();
ctx.rotate((m*Math.PI/30) + (s*Math.PI/1800));
ctx.moveTo(-30,0);
ctx.lineTo(160,0);
ctx.stroke();
ctx.restore(); ctx.save();
//时针
ctx.strokeStyle = "red";
ctx.lineWidth = 4;
ctx.beginPath();
ctx.rotate((h*Math.PI/6)+(m*Math.PI/360) + (s*Math.PI/21600));
ctx.moveTo(-10,0);
ctx.lineTo(150,0);
ctx.stroke();
ctx.restore(); ctx.beginPath();
ctx.arc(0,0,5,0,360,false);
ctx.closePath();
ctx.fillStyle = "#ebebeb";
ctx.fill();
ctx.stroke(); ctx.restore(); //添加数字
for(i = 0;i<12;i++){
angle = i * 30;
// 转换为弧度制,Math.sin、Math.cos都接受弧度制单位
angle = angle*Math.PI/180;;
font = (i + 3 > 12)?i+3-12 : i+3;
fontX = 244+Math.round(Math.cos(angle)*(r-60));
fontY = 256+Math.round(Math.sin(angle)*(r-60));
ctx.font = 'bold 14px 微软雅黑';
ctx.fillText(font+'',fontX,fontY);
} ctx.restore();
window.requestAnimationFrame(clock);
//外圆框
ctx.lineWidth=4;
ctx.strokeStyle="gray";
ctx.beginPath();
ctx.arc(250,250,r,0,Math.PI*2,true);
ctx.stroke();
ctx.restore();
ctx.restore();
}
window.requestAnimationFrame(clock); clock ();
</script>
</body>
</html>

效果图:

canvas-绘制时钟