본문 바로가기

HTML5/Img Cnt Rotate

Rotate Image about center

HTML5 Example, Rotate Image about center


HTML5의 Canvas에서 이미지를 회전할 때 이미지의 중심을 기준으로 회전하는 방법


ctx.save();

ctx.translate(x,y);                         // 이미지 중심이 위치할 캔바스 상의 좌표

ctx.rotate(heading);                      // 회전각(라디안)

ctx.drawImage(offCanvas,-10,-35);    // -(이미지 폭의 절반), -(이미지 높이의 절반)

ctx.restore();


오브젝트가 상승할 때는 기수를 위로 향하고 하강할 때는 기수를 아래로 향하도록 오브젝트를 회전하는 예

<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>비행방향으로 기수를 돌리는 예제</title>
<script type="text/javascript">
function Vector2D(x,y) {
    
    this.x = x;
    this.y = y;
     
    this.add = function(v2d) {
        return new Vector2D(this.x + v2d.x, this.y + v2d.y);
    }
     
    this.sub = function(v2d) {
        return new Vector2D(this.x - v2d.x, this.y - v2d.y);
    }
     
    this.multiply = function(len) {
        return new Vector2D(this.x * len, this.y * len);
    }
     
    this.normalize = function() {
        var len = Math.sqrt((this.x * this.x + this.y * this.y));
        return new Vector2D(this.x/len, this.y/len);
    }
}

window.onload = function() {
	init();
}

var imgData;
var offCanvas;
var mainCanvas;
var x = 0;
var y = 0;
var vy = -10;

function init() {
	//alert('init');
	
	mainCanvas = document.getElementById('canvas1');
	x = mainCanvas.width/2;
	y = mainCanvas.height-70;
	
	offCanvas = document.createElement('canvas');
	var offCtx = offCanvas.getContext('2d');
	
	offCtx.height = 70;
	offCtx.width = 20;
	
	offCtx.beginPath();
	offCtx.moveTo(10,0);
	offCtx.lineTo(20,70);
	offCtx.lineTo(0,70);
	offCtx.fill();
	
	setInterval(gameLoop, 40);
}

function gameLoop(){
	drawObj();
}

var preV = new Vector2D(0,0);
var curV = new Vector2D(0,0);

function drawObj() {
	if(!mainCanvas) mainCanvas = document.getElementById('canvas1');
	var ctx = mainCanvas.getContext('2d');
	ctx.clearRect(0,0,mainCanvas.width,mainCanvas.height);
	
	preV.x = x;
	preV.y = y;

	vy+=0.2;
	y += vy;
	
	curV.x = x;
	curV.y = y;

	var directV = curV.sub(preV);
	var uV = directV.normalize();
	var heading = Math.atan2(uV.y,uV.x)-(Math.PI/180*270);

	ctx.save();
	ctx.translate(x,y);
	ctx.rotate(heading);
	ctx.drawImage(offCanvas,-10,-35);
	ctx.restore();
}
</script>
</head>
<body>
<canvas id="canvas1" width="500" height="500"></canvas>
</body>
</html>