1. 程式人生 > >HTML5(六)html5<canvas帶音效的時鐘>

HTML5(六)html5<canvas帶音效的時鐘>

html5的canvas實現帶音效的時鐘

<!DOCTYPE html>
<html>
	<head>
		<title>canvas</title>
		<style>
			canvas{
				background:#eee;
			}
		</style>
		<script>
			window.onload=function(){
				var canvas = document.getElementById("canvas");
				var cobj = canvas.getContext("2d");
				var originx=200;
				var originy=200;
				var radius=100;
				var audio = document.getElementById("audio");
				audio.ontimeupdate=function(){
					if(audio.currentTime>=0.1){
						audio.pause();
					}
				}
				

				setInterval(function(){
					cobj.clearRect(0,0,400,400);
					audio.currentTime=0;
					audio.play();
					//陰影
					cobj.shadowColor="#888";
					cobj.shadowOffsetX=1;
					cobj.shadowOffsetY=1;
					cobj.shadowBlur=3;

					//漸變色
					var colorObj = cobj.createRadialGradient(originx,originy,1,originx,originy,100);
					colorObj.addColorStop(0,"#efefef");
					colorObj.addColorStop(1,"#cecece");
					cobj.fillStyle=colorObj;
					cobj.lineWidth=8;
					cobj.strokeStyle=colorObj;

					
					cobj.beginPath();
					cobj.arc(originx,originy,radius,0,2*Math.PI);
					cobj.stroke();
					cobj.fill();

					//去掉陰影
					cobj.shadowColor="#888";
					cobj.shadowOffsetX=0;
					cobj.shadowOffsetY=0;
					cobj.shadowBlur=0;

					//畫刻度
					drawMark();

					//畫針
					var date = new Date();
					var ha = date.getHours()*30+(date.getMinutes()*6/12)-90;
					var ma = date.getMinutes()*6-90;
					var sa = date.getSeconds()*6-90;
					//時針
					drawPointer(55,ha,4,"#000");
					//分針
					drawPointer(65,ma,3,"#888");
					//秒針
					drawPointer(75,sa,2,"#ff0000");

					//畫小圓
					cobj.shadowColor="#888";
					cobj.shadowOffsetX=1;
					cobj.shadowOffsetY=1;
					cobj.shadowBlur=3;
					cobj.beginPath();
					cobj.fillStyle="#aaa";
					cobj.arc(originx,originy,4,0,2*Math.PI);
					cobj.fill();
				},1000);

				//畫針的函式
				function drawPointer(radius,angle,width,color){
					cobj.lineWidth=width;
					cobj.strokeStyle=color;
					cobj.beginPath();
					cobj.moveTo(originx,originy);
					cobj.lineTo(originx+radius*Math.cos(angle*Math.PI/180),originy+radius*Math.sin(angle*Math.PI/180));
					cobj.stroke();
				}

				//畫刻度的函式
				function drawMark(){
					for(var i=0;i<60;i++){
						var angle=i*6*Math.PI/180;
						var radius1=radius-4;
						var lw=2;
						if(i%5==0){
							radius1=radius-8;
							lw=4;
						}

						cobj.strokeStyle="#888";
						cobj.lineWidth=lw;
						cobj.beginPath();
						cobj.moveTo(originx+radius*Math.cos(angle),originy+radius*Math.sin(angle));
						cobj.lineTo(originx+radius1*Math.cos(angle),originy+radius1*Math.sin(angle));
						cobj.stroke();
					}
				}
			}
		</script>
	</head>
	<body>
		<canvas width="400px" height="400px" id="canvas">
			請您升級瀏覽器
		</canvas>
		<audio src="1.wav" id="audio">
		</audio>
	</body>
</html>