HTML5에서 변환행렬을 적용하여 회전하는 효과를 내는 예
테스트 환경: HTML5, Eclipse, Google Chrome, Javascript
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>변환행렬을 적용한 예</title>
<script type="text/javascript">
var canvas = null;
var ctx = null;
window.onload = function() {
canvas = document.getElementById('MyCanvas');
ctx =canvas.getContext('2d');
drawShape();
}
/* 회전행렬을 이용하여 회전변환을 설정한 예 */
function drawShape(){
var sin = Math.sin(Math.PI/6);
var cos = Math.cos(Math.PI/6);
var x = canvas.width/2;
var y = canvas.height/2;
ctx.strokeStyle = "black";
ctx.beginPath();
for (var i=0; i <= 12; i++) {
ctx.translate(x, y);
ctx.transform(cos, sin, -sin, cos, 0, 0); // html5에서 회전행렬을 적용하는 예
ctx.translate(-x, -y);
ctx.moveTo(x, y);
ctx.lineTo(x+100, y);
}
ctx.stroke();
}
</script>
</head>
<body>
<canvas id="MyCanvas" width="400" height="300" style="border:1px dotted black;">
HTML5 Canvas를 지원하지 않는 브라우저입니다.
</canvas>
</body>
</html>
ctx.rotate()를 이용하여 회전변환을 적용한 예 ( 변환이 누적되어 나타나는 예)
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>변환행렬이 아닌 rotate()를 사용하여 회전변환을 적용한 예</title>
<script type="text/javascript">
var canvas = null;
var ctx = null;
window.onload = function() {
canvas = document.getElementById('MyCanvas');
ctx =canvas.getContext('2d');
drawShape();
}
/* ctx에 설정한 변환은 그 상태가 저장되기 때문에 이후에 캔바스에 그리는 모든
* 내용에 해당 변환이 적용되어 나타난다.
* 아래의 코드는 매 루프마다 30도 회전변환을 적용하고 있기 때문에 기존 변환에
* 계속 누적되어 회전량이 매 루프마다 증가하는 효과를 가진다.
*/
function drawShape(){
var x = ctx.canvas.width/2;
var y = ctx.canvas.height/2;
ctx.strokeStyle = "black";
ctx.beginPath();
for (var i=0; i <= 12; i++) {
ctx.translate(x, y);
//ctx.transform(cos, sin, -sin, cos, 0, 0);
ctx.rotate(30*Math.PI/180); // 매 루프마다 30도씩 누적되는 효과를 가짐
ctx.translate(-x, -y);
ctx.moveTo(x, y);
ctx.lineTo(x+100,y);
}
ctx.stroke();
}
</script>
</head>
<body>
<canvas id="MyCanvas" width="400" height="300" style="border:1px dotted black;">
HTML5 Canvas를 지원하지 않는 브라우저입니다.
</canvas>
</body>
</html>
ctx.save(), ctx.restore()를 사용하여 변환이 누적되지 않도록 설정하는 예
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>ctx.rotate()를 이용하여 회전변환을 적용한 예</title>
<script type="text/javascript">
var canvas = null;
var ctx = null;
window.onload = function() {
canvas = document.getElementById('MyCanvas');
ctx =canvas.getContext('2d');
drawShape();
}
function drawShape(){
var x = ctx.canvas.width/2;
var y = ctx.canvas.height/2;
ctx.strokeStyle = "black";
ctx.beginPath();
/* rotate()를 사용하여 변환을 적용한 후 그 변환을 해제하는 예
* ctx.save(), ctx.restore()를 적용하여 변환 적용 전의 상태를 저장하고 사용함
*/
for (var i=0; i <= 12; i++) {
ctx.save();
ctx.translate(x, y);
//ctx.transform(cos, sin, -sin, cos, 0, 0);
ctx.rotate(i*30*Math.PI/180); // 회전량이 누적되지 않으므로 개발자가 누적 효과를 구현해야 함
ctx.translate(-x, -y);
ctx.moveTo(x, y);
ctx.lineTo(x+100,y);
ctx.restore();
}
ctx.stroke();
}
</script>
</head>
<body>
<canvas id="MyCanvas" width="400" height="300" style="border:1px dotted black;">
HTML5 Canvas를 지원하지 않는 브라우저입니다.
</canvas>
</body>
</html>