여러분이 사용하고 계신 브라우저는 HTML5를 지원하지 않기 때문에 몇몇 요소가 제대로 보이도록 JScript를 사용하고 있습니다. 하지만 여러분의 브라우저 설정에서 스크립트 기능이 꺼져있으므로, 현재 페이지를 제대로 확인하시려면 스크립트 기능을 켜주셔야 합니다. HTML Canvas - 변환

HTML Canvas – 변환

4주전 작성

Canvas 변환

Canvas 변환 기능을 사용하면 도형을 그리기 전에 캔버스의 좌표계를 변경할 수 있다. 이를 통해 도형을 회전, 확대/축소, 이동시킬 수 있다.

기본 변환 메서드

Canvas에서 제공하는 주요 변환 메서드는 다음과 같다.

  • translate(x, y) – 캔버스의 원점을 이동시킨다
  • rotate(angle) – 캔버스를 회전시킨다
  • scale(scaleX, scaleY) – 캔버스를 확대/축소시킨다
  • transform(a, b, c, d, e, f) – 변환 행렬을 적용한다
  • setTransform(a, b, c, d, e, f) – 변환 행렬을 설정한다

translate() – 좌표계 이동

translate() 메서드는 캔버스의 원점(0,0)을 새로운 위치로 이동시킨다.

<canvas id="myCanvas1" width="300" height="150" style="border:1px solid #d3d3d3;">
브라우저가 HTML5 Canvas를 지원하지 않습니다.
</canvas>
<script>
var c = document.getElementById("myCanvas1");
var ctx = c.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(10, 10, 100, 50);
ctx.translate(70, 70);
ctx.fillStyle = "blue";
ctx.fillRect(10, 10, 100, 50);
</script>

이 예제에서는 먼저 빨간색 사각형을 그린 후 translate(70, 70)으로 좌표계를 이동시킨다. 그 다음 파란색 사각형을 동일한 좌표(10, 10)에 그리지만 실제로는 이동된 좌표계에 따라 다른 위치에 그려진다.

rotate() – 회전

rotate() 메서드는 캔버스를 지정된 각도만큼 회전시킨다. 각도는 라디안 단위로 지정한다.

<canvas id="myCanvas2" width="300" height="150" style="border:1px solid #d3d3d3;">
브라우저가 HTML5 Canvas를 지원하지 않습니다.
</canvas>
<script>
var c = document.getElementById("myCanvas2");
var ctx = c.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(100, 20, 100, 50);
ctx.rotate(20 * Math.PI / 180);
ctx.fillStyle = "blue";
ctx.fillRect(100, 20, 100, 50);
</script>

이 예제는 빨간색 사각형을 그린 후 캔버스를 20도 회전시키고 파란색 사각형을 그린다. 회전은 캔버스의 원점(0,0)을 중심으로 수행된다.

중심점을 기준으로 회전

도형의 중심을 기준으로 회전시키려면 translate()와 rotate()를 조합하여 사용한다.

<canvas id="myCanvas3" width="300" height="150" style="border:1px solid #d3d3d3;">
브라우저가 HTML5 Canvas를 지원하지 않습니다.
</canvas>
<script>
var c = document.getElementById("myCanvas3");
var ctx = c.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(100, 50, 100, 50);
ctx.translate(150, 75);
ctx.rotate(45 * Math.PI / 180);
ctx.fillStyle = "blue";
ctx.fillRect(-50, -25, 100, 50);
</script>

이 예제에서는 먼저 빨간색 사각형을 그린 후, 사각형의 중심점(150, 75)으로 좌표계를 이동시키고 45도 회전시킨다. 그 다음 파란색 사각형을 중심을 기준으로 한 좌표로 그린다.

scale() – 확대/축소

scale() 메서드는 캔버스를 확대하거나 축소시킨다.

<canvas id="myCanvas4" width="300" height="150" style="border:1px solid #d3d3d3;">
브라우저가 HTML5 Canvas를 지원하지 않습니다.
</canvas>
<script>
var c = document.getElementById("myCanvas4");
var ctx = c.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(20, 20, 50, 50);
ctx.scale(2, 2);
ctx.fillStyle = "blue";
ctx.fillRect(20, 20, 50, 50);
</script>

이 예제는 빨간색 사각형을 그린 후 캔버스를 2배로 확대한다. 그 다음 파란색 사각형을 동일한 좌표에 그리지만 확대된 좌표계로 인해 더 크고 다른 위치에 그려진다.

비례 확대/축소

x축과 y축을 다르게 확대/축소하여 도형을 변형시킬 수 있다.

<canvas id="myCanvas5" width="300" height="150" style="border:1px solid #d3d3d3;">
브라우저가 HTML5 Canvas를 지원하지 않습니다.
</canvas>
<script>
var c = document.getElementById("myCanvas5");
var ctx = c.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(20, 20, 50, 50);
ctx.scale(2, 0.5);
ctx.fillStyle = "blue";
ctx.fillRect(20, 20, 50, 50);
</script>

이 예제는 x축을 2배로 확대하고 y축을 0.5배로 축소하여 파란색 사각형을 가로로 늘어난 모양으로 그린다.

save()와 restore() 메서드

변환을 적용하기 전에 현재 상태를 저장하고 나중에 복원할 수 있다.

<canvas id="myCanvas6" width="300" height="150" style="border:1px solid #d3d3d3;">
브라우저가 HTML5 Canvas를 지원하지 않습니다.
</canvas>
<script>
var c = document.getElementById("myCanvas6");
var ctx = c.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(20, 20, 50, 50);
ctx.save();
ctx.translate(100, 0);
ctx.scale(2, 2);
ctx.fillStyle = "blue";
ctx.fillRect(20, 20, 50, 50);
ctx.restore();
ctx.fillStyle = "green";
ctx.fillRect(20, 80, 50, 50);
</script>

이 예제에서는 save()로 현재 상태를 저장한 후 변환을 적용하여 파란색 사각형을 그린다. 그 다음 restore()로 저장된 상태로 되돌린 후 녹색 사각형을 그린다.

복합 변환

여러 변환을 조합하여 복잡한 효과를 만들 수 있다.

<canvas id="myCanvas7" width="300" height="150" style="border:1px solid #d3d3d3;">
브라우저가 HTML5 Canvas를 지원하지 않습니다.
</canvas>
<script>
var c = document.getElementById("myCanvas7");
var ctx = c.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(100, 50, 50, 50);
ctx.save();
ctx.translate(125, 75);
ctx.rotate(30 * Math.PI / 180);
ctx.scale(1.5, 1.5);
ctx.fillStyle = "blue";
ctx.fillRect(-25, -25, 50, 50);
ctx.restore();
</script>

이 예제는 이동, 회전, 확대를 모두 적용하여 파란색 사각형을 변형시킨다.

transform() 메서드

transform() 메서드는 현재 변환 행렬에 새로운 변환을 추가한다.

<canvas id="myCanvas8" width="300" height="150" style="border:1px solid #d3d3d3;">
브라우저가 HTML5 Canvas를 지원하지 않습니다.
</canvas>
<script>
var c = document.getElementById("myCanvas8");
var ctx = c.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(20, 20, 50, 50);
ctx.transform(1, 0.5, 0, 1, 0, 0);
ctx.fillStyle = "blue";
ctx.fillRect(20, 20, 50, 50);
</script>

transform() 메서드의 매개변수는 변환 행렬의 값들이다. 이 예제는 y축 기울임 변환을 적용하여 파란색 사각형을 기울어진 모양으로 그린다.

setTransform() 메서드

setTransform() 메서드는 현재 변환을 재설정한다.

<canvas id="myCanvas9" width="300" height="150" style="border:1px solid #d3d3d3;">
브라우저가 HTML5 Canvas를 지원하지 않습니다.
</canvas>
<script>
var c = document.getElementById("myCanvas9");
var ctx = c.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(20, 20, 50, 50);
ctx.scale(2, 2);
ctx.fillStyle = "blue";
ctx.fillRect(20, 20, 50, 50);
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.fillStyle = "green";
ctx.fillRect(20, 20, 50, 50);
</script>

이 예제에서는 scale() 변환을 적용한 후 setTransform()으로 변환을 초기화한다. 녹색 사각형은 변환이 적용되지 않은 상태로 그려진다.

💡 Canvas 변환 팁:
• 변환은 누적되므로 save()와 restore()를 적절히 사용하여 상태를 관리하자
• 회전 각도는 라디안 단위로 지정한다 (도수 × π / 180)
• 복잡한 변환을 적용할 때는 변환 순서가 중요하다

애니메이션과 변환

변환을 애니메이션과 결합하면 동적인 효과를 만들 수 있다.

<canvas id="myCanvas10" width="300" height="150" style="border:1px solid #d3d3d3;">
브라우저가 HTML5 Canvas를 지원하지 않습니다.
</canvas>
<script>
var c = document.getElementById("myCanvas10");
var ctx = c.getContext("2d");
var angle = 0;
function draw() {
ctx.clearRect(0, 0, c.width, c.height);
ctx.save();
ctx.translate(150, 75);
ctx.rotate(angle);
ctx.fillStyle = "red";
ctx.fillRect(-25, -25, 50, 50);
ctx.restore();
angle += 0.05;
requestAnimationFrame(draw);
}
draw();
</script>

이 예제는 캔버스 중앙에서 회전하는 빨간색 사각형을 보여준다. 매 프레임마다 각도를 증가시켜 연속적인 회전 효과를 만든다.

Canvas 변환 기능을 마스터하면 정적인 도형을 동적이고 흥미로운 그래픽으로 변환할 수 있다. 이러한 기술은 게임, 데이터 시각화, 인터랙티브 애플리케이션 등에서 광범위하게 활용된다.

참고
Mingg`s Diary
밍구
공부 목적 블로그