• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
梦见艾七
博客园    首页    新随笔    联系   管理    订阅  订阅

用canvas画一个时钟

h5部分:

		<canvas id="canvas" width="400" height="400">
			您的浏览器不支持canvas,请升级浏览器。
		</canvas>

 javascript部分:

<script type="text/javascript">
	var canvas = document.getElementById("canvas");
	var ctx = canvas.getContext("2d");
	canvas.style.border = "1px solid #ccc";
	function drawClock(){
		ctx.clearRect(0,0,400,400);
		ctx.strokeStyle = "#dea286";
		ctx.lineWidth = "10";
		ctx.beginPath();
		ctx.arc(200,200,150,0*Math.PI/180,360*Math.PI/180,false);
		ctx.stroke();
		
		//时刻度
		for(var i = 0; i < 12; i++){
			ctx.save();
			ctx.lineWidth = "7";
			ctx.strokeStyle = "#dea286";
			ctx.translate(200,200);
			ctx.rotate(i*30*Math.PI/180);
			ctx.beginPath();
			ctx.moveTo(0, -125);
			ctx.lineTo(0, -140);
			ctx.closePath();
			ctx.stroke();
			ctx.closePath();
			ctx.restore();
		}
		//数字
		for (var i=0;i<12;i++) {
			ctx.beginPath();
			var txt = i<1 ? 12 : i;
			ctx.font = "12px";
			ctx.lineWidth = "2";
			ctx.strokeStyle = "#a5735c";
			var x = 195+Math.sin(i*30*Math.PI/180)*115;
			var y = 205-Math.cos(i*30*Math.PI/180)*115;
			ctx.strokeText(txt,x,y);
		}
		//分刻度
		for(var i = 0; i < 60; i++){
			ctx.save();
			ctx.lineWidth = "4";
			ctx.strokeStyle = "#dea286";
			ctx.translate(200,200);
			ctx.rotate(i*6*Math.PI/180);
			ctx.beginPath();
			ctx.moveTo(0, -135);
			ctx.lineTo(0, -140);
			ctx.closePath();
			ctx.stroke();
			ctx.restore();
		}
		
	        //获取时间
		var date1 = new Date();
		var s = date1.getSeconds();
		var m = date1.getMinutes();
		var h = date1.getHours();
		
		//时针
		ctx.save();
		ctx.lineWidth = "7";
		ctx.strokeStyle = "#a5735c";
		ctx.translate(200,200);
		ctx.rotate(h*30*Math.PI/180);
		ctx.beginPath();
		ctx.moveTo(0,-60);
		ctx.lineTo(0,8);
		ctx.closePath();
		ctx.stroke();
		ctx.restore();
		//分针
		ctx.save();
		ctx.lineWidth = "5";
		ctx.strokeStyle = "#dea286";
		ctx.translate(200,200);
		ctx.rotate(m*6*Math.PI/180);
		ctx.beginPath();
		ctx.moveTo(0,-80);
		ctx.lineTo(0,10);
		ctx.closePath();
		ctx.stroke();
		ctx.restore();
		//秒针
		ctx.save();
		ctx.lineWidth = "3";
		ctx.strokeStyle = "#e9c6c0";
		ctx.translate(200,200);
		ctx.rotate(s*6*Math.PI/180);
		ctx.beginPath();
		ctx.moveTo(0,-120);
		ctx.lineTo(0,12);
		ctx.closePath();
		ctx.stroke();
		//指针中心的小圆点
		ctx.beginPath();
		ctx.arc(0,0,4,0*Math.PI/180,360*Math.PI/180,false);
		ctx.closePath();
		ctx.fillStyle = "#aaaaaa";
		ctx.fill();
		ctx.stroke();
		ctx.restore();
	}
	drawClock();
	setInterval(drawClock,1000);
</script>

  效果图:

 

posted on 2017-08-08 15:03  梦见艾七  阅读(152)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3