JavaScript:使用cavas製作圖片時鐘

/* cavas圖片時鐘
* handImage={
		secHand:"*.png",minHand:"*.png",hourHand:"*.png",dial:"*.png"
	}
*handImage設置時分秒和錶盤的圖片
*handPositon:{
		hourHand:{width:20,height:139,center:20},
		minHand:{width:20,height:172,center:20},
		secHand:{width:18,height:257,center:71}
	}
*handPositon設置時分秒指針的寬、長(高)和中心點的高度
*/
function imgClock(canvas,handImage,handPositon) {
	var ctx=canvas.getContext('2d');
	var width=canvas.width;
	var height=canvas.height;
	var centerX=width/2;
	var centerY=height/2;
	var dial=new Image();
	var hourHand=new Image();
	var minHand=new Image();
	var secHand=new Image();
	dial.src=handImage.dial;
	hourHand.src=handImage.hourHand;
	minHand.src=handImage.minHand;
	secHand.src=handImage.secHand;
	hourHand.width=handPositon.hourHand.width;
	hourHand.height=handPositon.hourHand.height;
	hourHandCenter=handPositon.hourHand.center;
	minHand.width=handPositon.minHand.width;
	minHand.height=handPositon.minHand.height;
	minHandCenter=handPositon.minHand.center;
	secHand.width=handPositon.secHand.width;
	secHand.height=handPositon.secHand.height;
	secHandCenter=handPositon.secHand.center;
	dial.onload=function(){
		function drawClock(){
			ctx.clearRect(0,0,canvas.width,canvas.height);
			var now = new Date();
			var sec = now.getSeconds();
			var min = now.getMinutes();
			var hour = now.getHours();
			hour += min/60;
			ctx.drawImage(dial,0,0,width,height);//繪製錶盤
			
			//時針設置
			ctx.save();//存貯上一級(save之前)的狀態,入棧
			ctx.translate(centerX,centerY);//向右、向下平移到鐘錶中心
			ctx.rotate(hour*30*Math.PI/180);//旋轉角度
			ctx.drawImage(hourHand,-hourHand.width/2,hourHandCenter-hourHand.height,hourHand.width,hourHand.height);
			ctx.restore();//恢復到上一級(save之前)狀態,防止本次操作對後續操作有影響
			
			//分針設置
			ctx.save();//重置
			ctx.translate(centerX,centerY);
			ctx.rotate(min*6*Math.PI/180);						
			ctx.drawImage(minHand,-minHand.width/2,minHandCenter-minHand.height,minHand.width,minHand.height);
			ctx.restore();
			
			//秒針設置
			ctx.save();
			ctx.translate(centerX,centerY);
			ctx.rotate(sec*6*Math.PI/180);
			ctx.drawImage(secHand,-secHand.width/2,secHandCenter-secHand.height,secHand.width,secHand.height);			
			ctx.restore();						
		}
		drawClock();
		setInterval(drawClock,500);
	}
}

 

posted @ 2019-01-11 08:49  漫冬飄雪  阅读(177)  评论(0编辑  收藏  举报