>  기사  >  웹 프론트엔드  >  HTML5 컴포넌트 Canvas를 이용한 전자시계의 그래픽 코드에 대한 자세한 소개

HTML5 컴포넌트 Canvas를 이용한 전자시계의 그래픽 코드에 대한 자세한 소개

黄舟
黄舟원래의
2017-03-03 16:24:221438검색

기본 아이디어:

먼저 직사각형 배경을 그리고 색상을 회색으로 설정합니다. 배경에 간단한 직사각형 외부 테두리를 그린 후

내부 테두리를 그린 후 선택한 이미지를 전자시계 내부의 배경 이미지로 불러옵니다. 그런 다음 시계 눈금 그리기를 시작하고

분 눈금을 그리고 마지막으로 현재 시스템 시간을 가져와 시, 분, 초에 대한 세 개의 핸들을 그립니다.

기술적 포인트:

HTML5의 Canvas 2D를 사용하여 개체를 그립니다. 주로 context.save() 및 context.restore() 메서드를 사용하여 저장합니다.

상태 그리기 및 그리기 상태 재설정, Transform 및 fillRect() 메서드를 사용하여 시계 및 분 눈금을 그립니다. 배경 이미지를 그리려면

drawImage() 메서드를 사용하고, 시간 표시를 새로 고치려면 setTimeout() 메서드를 사용합니다.

상세 코드 설명:

HTML5 Canvas 그리기 객체를 얻는 코드는 다음과 같습니다.

var canvas = document.getElementById("canvas1");
ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, 500, 500);

시계 눈금을 그리는 코드는 다음과 같습니다.

		    var sin = Math.sin(Math.PI/6);  
		    var cos = Math.cos(Math.PI/6); 
		    ctx.translate(245, 245);
		    for (var i=0; i <= 12; i++) {  
		    	// top
				ctx.fillRect(160,-7.5,30,10);
				ctx.strokeRect(160,-7.5,30,10);
				ctx.transform(cos, sin, -sin, cos, 0, 0);  	
		    }

분, 분 눈금을 그리는 코드는 다음과 같습니다.

		    var sin = Math.sin(Math.PI/30);  
		    var cos = Math.cos(Math.PI/30); 
		    for (var i=0; i <= 60; i++) {  
				ctx.fillRect(170,-5,10,2);
				ctx.transform(cos, sin, -sin, cos, 0, 0); 	
		    }

저장 상태 코드는 다음과 같습니다.

ctx.translate(245, 245);
ctx.save();

그리기 상태를 재개하는 코드는 다음과 같습니다.

ctx.restore();

실행 효과는 다음과 같습니다.


프로그램의 전체 소스 코드는 다음과 같습니다.



<script>
	window.onload = function() {
		clockHand();
	};
	
	function clockHand() {
		var canvas = document.getElementById("canvas1");
		ctx = canvas.getContext("2d");
		ctx.clearRect(0, 0, 500, 500);
		
		// create background rectangle
		// ctx.lineWidth = 10;  
		ctx.fillStyle = "gray";
		ctx.fillRect(0,0,500,500);
		
		// draw frame
		ctx.lineWidth = 10;  
		ctx.strokeStyle = "green";
		ctx.strokeRect(0,0,500,500);
		
		// draw author infomation
		ctx.fillStyle = "blue";
		ctx.font = "20px Times New Roman";
		ctx.fillText("-created by gloomyfish", 150, 30);
		
		// draw inner rectangle
		ctx.lineWidth = 10;  
		ctx.strokeStyle = "black";
		ctx.strokeRect(45,45,400,400);
		
		// create background image
		var img=new Image();
		img.src="background.png";
		img.onload = function() { 
		    ctx.drawImage(img,45,45,400,400);
		    ctx.save();
			// draw marker unit
			ctx.lineWidth = 2;
		    ctx.fillStyle = "purple";
		    ctx.strokeStyle = "black";
		    var sin = Math.sin(Math.PI/6);  
		    var cos = Math.cos(Math.PI/6); 
		    ctx.translate(245, 245);
		    for (var i=0; i &lt;= 12; i++) {  
		    	// top
				ctx.fillRect(160,-7.5,30,10);
				ctx.strokeRect(160,-7.5,30,10);
				ctx.transform(cos, sin, -sin, cos, 0, 0);  	
		    }
		    
		    // transform back center point
		    
		    // ctx.translate(245, 245);
		    var sin = Math.sin(Math.PI/30);  
		    var cos = Math.cos(Math.PI/30); 
		    for (var i=0; i &lt;= 60; i++) {  
				ctx.fillRect(170,-5,10,2);
				ctx.transform(cos, sin, -sin, cos, 0, 0); 	
		    }
		    ctx.restore();
		    // top
			ctx.fillText("12", 233,100);
			
			// bottom
			ctx.fillText("6", 240,400);
			
			// left
			ctx.fillText("9", 90,252);
			
			// right
			ctx.fillText("3", 395,250);
			
			// get time
			ctx.save();
			ctx.translate(245, 245);
			ctx.save();
			
			// dynamic show time
			var now=new Date();
			var hrs=now.getHours();
			var min=now.getMinutes();
			var sec=now.getSeconds();

			//Draw hour hand
			ctx.rotate(Math.PI/6*(hrs+(min/60)+(sec/3600)));
			ctx.beginPath();
			ctx.moveTo(0,10);
			ctx.lineTo(0,-60);
			ctx.stroke();
			ctx.restore();
			ctx.save();
			
			//Draw minute hand
			ctx.rotate(Math.PI/30*(min+(sec/60)));
			ctx.beginPath();
			ctx.moveTo(0,20);
			ctx.lineTo(0,-110);
			ctx.stroke();
			ctx.restore();
			ctx.save();
			
			//Draw second hand
			ctx.rotate(Math.PI/30*sec);
			ctx.strokeStyle="#E33";
			ctx.lineWidth = 2;
			ctx.beginPath();
			ctx.moveTo(0,20);
			ctx.lineTo(0,-110);
			ctx.stroke();
			ctx.restore();
			
			// finally store to originall point
			ctx.restore();
			setTimeout(clockHand,1000);
		};
	}
</script>


	electronic clock

단점:

매번 이미지 개체를 새로고침하고 로드하는 것이 별로 좋지 않습니다. Google 브라우저에서 테스트해 봤습니다.

에서 위 코드를 실행하는 것이 좋습니다.

구글 브라우저.

위 내용은 전자시계를 구현하기 위한 HTML5 컴포넌트 Canvas의 그래픽과 텍스트 코드에 대한 자세한 소개입니다. 더 많은 관련 내용은 PHP 중국어 홈페이지(www.php.cn)를 참고해주세요!


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.