html5 Canvas 钟表

阅读更多

html5 canvas 画钟表例子,参考别人的例子,整理完成,有详细注释

参考:http://www.html5tricks.com/demo/html5-canvas-circle-clock/index.html

 




  
  
  JS Bin




 

	var c = document.getElementById('myCanvas').getContext('2d');
	function clock(){
		//清空画布
		c.clearRect(0,0,400,400);
		var data = new Date();
		var sec =data.getSeconds();
		var min =data.getMinutes();
		var hour=data.getHours();
        var year=data.getFullYear();
        var month=data.getMonth()+1;
        var day =data.getDate();

		//保存当前环境的状态
		c.save();
		//重新映射画布上的 (0,0) 位置
		c.translate(200,200);
		//旋转当前绘图(逆时针旋转1/4的圆路径)
		c.rotate(-2*Math.PI/4);

		//分钟刻度线(画60个刻度线)
		for(var i=0;i<60;i++){
			c.beginPath();
			c.strokeStyle = "#f00";
			c.lineWidth = 5;
			c.moveTo(110,0);
			c.lineTo(120,0);
			c.stroke();
			//每个6deg画一个时钟刻度线(顺时针旋转1/60的圆路径)
			c.rotate(2*Math.PI/60);
			c.closePath();
		}

		//时钟刻度线(画12个刻度线)
		for(var i=0;i<12;i++){
			c.beginPath();
			c.strokeStyle = "#000";
			c.lineWidth = 8;
			c.moveTo(100,0);
			c.lineTo(120,0);
			c.stroke();
			//每个30deg画一个时钟刻度线(顺时针旋转1/12的圆路径)
			c.rotate(2*Math.PI/12);
			c.closePath();
		}

		c.rotate(-1);
		//时钟刻度数字(画12个刻度数字)
		for(var i=0;i<12;i++){
			c.beginPath();
			c.strokeStyle = "blue";
			c.lineWidth = 2 ;
            c.strokeText(i+1,0,90);
			//每个30deg画一个时钟刻度线
			c.rotate(2*Math.PI/12);
			c.closePath();
		}
		c.rotate(1);

		//时间显示
		c.rotate(2*Math.PI/4);
        c.font="30px 宋体";
        c.strokeText(year+"-"+month+"-"+day+" "+hour+":"+min+":"+sec,-130,180);
		c.rotate(-2*Math.PI/4);
		
		//外表盘
		c.beginPath();
		c.strokeStyle = "pink";
		c.lineWidth = 12 ;
		//画圆
		c.arc(0,0,135,0,Math.PI*2);
		c.stroke();
		c.closePath();

		//画时针
		hour = hour>12?hour-12:hour;
		c.beginPath();
		//保存当前环境的状态
		c.save();
		//顺时针旋转当前时针指向所形成的圆弧路径
		c.rotate(2*Math.PI/12*hour+2*Math.PI/12/60*min+2*Math.PI/12/3600*sec);
		c.strokeStyle = "yellowgreen";
		c.lineWidth = 4;
		c.moveTo(-20,0);
		c.lineTo(50,0);
		c.stroke();
		//返回之前保存过的路径状态和属性
		c.restore();
		c.closePath();

		//画分针
		c.beginPath();
		//保存当前环境的状态
		c.save();
		//顺时针旋转当前分针指向所形成的圆弧路径
		c.rotate(2*Math.PI/60*min+2*Math.PI/60/60*sec);
		c.strokeStyle = "springgreen";
		c.lineWidth = 3;
		c.moveTo(-30,0);
		c.lineTo(70,0);
		c.stroke();
		//返回之前保存过的路径状态和属性
		c.restore();
		c.closePath();

		//画秒针
		c.beginPath();
		//保存当前环境的状态
		c.save();
		//顺时针旋转当前秒针指向所形成的圆弧路径
		c.rotate(2*Math.PI/60*sec);
		c.strokeStyle = "red";
		c.lineWidth = 2 ;
		c.moveTo(-40,0);
		c.lineTo(120,0);
		c.stroke();
		//返回之前保存过的路径状态和属性
		c.restore();
		c.closePath();

		c.restore();
	}
	clock();
	setInterval(clock,1000);

 
html5 Canvas 钟表_第1张图片
 

  • html5 Canvas 钟表_第2张图片
  • 大小: 27.7 KB
  • 查看图片附件

你可能感兴趣的:(js,html5,canvas)