HTML5/Matrix example

HTML5 Image Rotation example

Soul-Learner 2012. 4. 18. 00:34

HTML5 캔바스에서 이미지를 회전하는 예

테스트 환경: HTML5, Eclipse, Google Chrome, Javascript

사용된 이미지 URL : https://t1.daumcdn.net/cfile/tistory/141E79414F8D8D4321

HTML5 Canvas를 지원하지 않는 브라우저입니다.


<!DOCTYPE html>

<html>

<head>

<meta charset="EUC-KR">

<title>HTML5 이미지 회전</title>

<style type="text/css">

#MyCanvas {  }

</style>

<script type="text/javascript">

var ctx = null;

var canvas = null;

var imgUrl = "https://t1.daumcdn.net/cfile/tistory/141E79414F8D8D4321";

window.onload=function() {

canvas = document.getElementById("MyCanvas");

ctx = canvas.getContext('2d');

rotation_test2();

}

/* 캔바스의 원점(좌상단 모서리)을 기준으로 한 회전 테스트 */

function rotation_test1() {

var img = new Image();

img.onload = function() {

ctx.drawImage(img, canvas.width/2-img.width/2, canvas.height/2-img.height/2);

ctx.rotate(20*Math.PI/180);

ctx.drawImage(img, canvas.width/2-img.width/2, canvas.height/2-img.height/2);

};

img.src = imgUrl;

}


/* 원하는 이미지의 중심을 기준으로 한 회전 */

function rotation_test2() {

var img = new Image();

img.onload = function() {

ctx.save();

ctx.drawImage(img, canvas.width/2-img.width/2, canvas.height/2-img.height/2);

ctx.translate(canvas.width/2, canvas.height/2);

ctx.rotate(45*Math.PI/180);

ctx.translate(-(canvas.width/2), -(canvas.height/2));

ctx.drawImage(img, canvas.width/2-img.width/2, canvas.height/2-img.height/2);

ctx.restore();

};

img.src = imgUrl;

}

</script>

</head>

<body>

<canvas id="MyCanvas" width="400" height="300" style="border:1px dotted black;">

HTML5 Canvas를 지원하지 않는 브라우저입니다.

</canvas>

</body>

</html>