HTML5 캔버스 이동, 확대/축소, 이미지 회전 및 텍스트 코드 세부정보

黄舟
풀어 주다: 2017-03-03 16:13:55
원래의
3093명이 탐색했습니다.

HTML5 Canvas는 그래픽 변환, 회전 및 크기 조정을 위한 API를 제공합니다.

번역(translate)

번역 좌표(x, y)는 (0,0)을 의미합니다. 좌표 (x, y)로 변환되고 원래 (0,0) 좌표는 (-x, -y)가 됩니다.

도표는 다음과 같습니다.


번역 후 원래 좌표점 p(ox, oy)의 좌표점은 p(ox-x, oy-y)이며 중심점은 (x, y)는

점 좌표가 (x, y)를 번역한 것입니다.

코드 데모:

// translate is move the startpoint to centera and back to top left corner
function renderText(width, height, context) {
    context.translate(width/ 2, height / 2);// 中心点坐标为(0, 0)
    context.font="18px Arial";
    context.fillStyle="blue";
    context.fillText("Please Press <Esc> to Exit Game",5,50);
    context.translate(-width/2,-height/2); // 平移恢复(0,0)坐标为左上角
    context.fillText("I&#39;m Back to Top",5,50);
}
로그인 후 복사


Scale

Scale(a, b)는 XY 축을 따라 개체의 크기를 각각 a*x, b*y 크기로 조정하는 것을 의미합니다. 효과는 사진과 같습니다:


// translation the rectangle.
function drawPath(context) {
    context.translate(200,200);
    context.scale(2,2);// Scale twice size of original shape
    context.strokeStyle= "green";
    context.beginPath();
    context.moveTo(0,40);
    context.lineTo(80,40);
    context.lineTo(40,80);
    context.closePath();
    context.stroke();
}
로그인 후 복사


회전(rotate)

회전각도회전(Math.PI/8)


회전 전 좌표 p(x, y)와 회전 후 해당 좌표 P(rx, ry)는

Rx = x * cos(-angle)- y * sin(-angle);
Ry = y * cos(-angle) + x * sin(-angle);
로그인 후 복사


회전90도는 다음과 같이 단순화할 수 있습니다.

Rx = y;
Ry = -x;
로그인 후 복사


Canvas의 기본 회전 방향은 시계 방향입니다. 데모 코드는 다음과 같습니다:

// new point.x = x * cos(-angle) -y * sin(-angle),
// new point.y = y * cos(-angle) +x * sin(-angle)
function renderRotateText(context) {
    context.font="24px Arial";
    context.fillStyle="red";
    context.fillText("i&#39;m here!!!",5,50);
    
    // rotate -90 degreee
    // context.rotate(-Math.PI/2);
    // context.fillStyle="blue";
    // context.fillText("i&#39;m here!!!", -400,30);
    
    // rotate 90 degreee
    context.rotate(Math.PI/2);
    context.fillStyle="blue";
    context.fillText("i&#39;m here!!!",350,-420);
    
    console.log(Math.sin(Math.PI/2));
    
    // rotae 90 degree and draw 10 lines
    context.fillStyle="green";
    for(var i=0; i<4;
 i++) {
        var x = (i+1)*20;
        var y = (i+1)*60;
        var newX = y;
        var newY =-x;  
        context.fillRect(newX,newY, 200, 6);
    }
}
로그인 후 복사


일반적인 접근 방식은 회전과 평행 이동을 함께 사용하고 먼저 좌표를 변경하는 것입니다. (0,0)중앙 위치로 이동

(폭/2, 높이/2) 그런 다음 rotate(Math.PI/2)완전 회전

을 사용합니다. 코드 예는 다음과 같습니다.

function saveAndRestoreContext(context) {
    context.save();
    context.translate(200,200);
    context.rotate(Math.PI/2);
    context.fillStyle="black";
    context.fillText("2D Context Rotate And Translate", 10, 10);
    context.restore();
    context.fillText("2D Context Rotate And Translate", 10, 10);
}
로그인 후 복사


모든 JavaScript 코드:

		var tempContext = null; // global variable 2d context
		window.onload = function() {
			var canvas = document.getElementById("target");
			canvas.width = 450;
			canvas.height = 450;
			
			if (!canvas.getContext) {
			    console.log("Canvas not supported. Please install a HTML5 compatible browser.");
			    return;
			}
			
			// get 2D context of canvas and draw image
			tempContext = canvas.getContext("2d");
			// renderText(canvas.width, canvas.height, tempContext);
			saveAndRestoreContext(tempContext);
			// drawPath(tempContext);
		}
		
		// translate is move the start point to centera and back to top left corner
		function renderText(width, height, context) {
			context.translate(width / 2, height / 2);
			context.font="18px Arial";
			context.fillStyle="blue";
			context.fillText("Please Press <Esc> to Exit Game",5,50);
			context.translate(-width / 2, -height / 2);
			context.fillText("I&#39;m Back to Top",5,50);
		}
		
		// translation the rectangle.
		function drawPath(context) {
			context.translate(200, 200);
			context.scale(2,2); // Scale twice size of original shape
			context.strokeStyle = "green";
			context.beginPath();
			context.moveTo(0, 40);
			context.lineTo(80, 40);
			context.lineTo(40, 80);
			context.closePath();
			context.stroke();
		}
		
		// new point.x = x * cos(-angle) - y * sin(-angle), 
		// new point.y = y * cos(-angle) + x * sin(-angle)
		function renderRotateText(context) {
			context.font="24px Arial";
			context.fillStyle="red";
			context.fillText("i&#39;m here!!!",5,50);
			
			// rotate -90 degreee
			// context.rotate(-Math.PI/2);
			// context.fillStyle="blue";
			// context.fillText("i&#39;m here!!!", -400,30);
			
			// rotate 90 degreee
			context.rotate(Math.PI/2);
			context.fillStyle="blue";
			context.fillText("i&#39;m here!!!", 350,-420);
			
			console.log(Math.sin(Math.PI/2));
			
			// rotae 90 degree and draw 10 lines
			context.fillStyle="green";
			for(var i=0; i<4; i++) {
				var x = (i+1)*20;
				var y = (i+1)*60;
				var newX = y;
				var newY = -x;	
				context.fillRect(newX, newY, 200, 6);
			}
		}
		
		function saveAndRestoreContext(context) {
			context.save();
			context.translate(200,200);
			context.rotate(Math.PI/2);
			context.fillStyle="black";
			context.fillText("2D Context Rotate And Translate", 10, 10);
			context.restore();
			context.fillText("2D Context Rotate And Translate", 10, 10);
		}
로그인 후 복사

위 내용은 HTML5 Canvas 번역, 그래픽 코드 확대/축소 및 회전 관련 내용은 PHP 중국어 홈페이지(www.php.cn)를 참고해주세요!


관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!