본문 바로가기

WebGL

WebGL Fundamentals > WebGL 2D : Rotation

https://webglfundamentals.org/webgl/lessons/webgl-2d-rotation.html

 

WebGL 2D Rotation

How to rotate in 2D

webglfundamentals.org

https://github.com/Myoungmin/WebGL_Fundamentals

 

GitHub - Myoungmin/WebGL_Fundamentals: WebGL 학습 프로젝트

WebGL 학습 프로젝트. Contribute to Myoungmin/WebGL_Fundamentals development by creating an account on GitHub.

github.com

 

 

WebGL 2D : Rotation

행렬을 적용하기 전에 ‘회전’의 기본 개념을 알아본다.

 

반지름이 1.0인 원을 뜻하는 단위원의 어느 지점에서 X와 Y값을 가져와서 지오메트리에 곱하기.

위치 회전의 결과가 x, y 평행이동에 추가적로 반영되는 것이다.

u_rotation이라는 단위원 X와 Y값을 담고 있는 uniform을 이용하도록 셰이더 변경

 

<script id="vertex-shader-2d" type="x-shader/x-vertex">
attribute vec2 a_position;
 
uniform vec2 u_resolution;
uniform vec2 u_translation;
uniform vec2 u_rotation;
 
void main() {
  // 위치 회전
  vec2 rotatedPosition = vec2(
     a_position.x * u_rotation.y + a_position.y * u_rotation.x,
     a_position.y * u_rotation.y - a_position.x * u_rotation.x);
 
  // 평행 이동 추가
  vec2 position = rotatedPosition + u_translation;
  //...

 

자바스크립트에서 uniform으로 두 값을 전달하도록 설정

  //...
 
  var rotationLocation = gl.getUniformLocation(program, "u_rotation");
 
  //...
 
  var rotation = [0, 1];
 
  //...
 
  // 장면 그리기
  function drawScene() {
 
    //...
 
    // 평행 이동 설정
    gl.uniform2fv(translationLocation, translation);
 
    // 회전 설정
    gl.uniform2fv(rotationLocation, rotation);
 
    // 지오메트리 그리기
    var primitiveType = gl.TRIANGLES;
    var offset = 0;
    var count = 18;  // 'F'의 삼각형 6개, 삼각형마다 점 3개
    gl.drawArrays(primitiveType, offset, count);
  }

 

단위원의 점은 sin과 cos이다.

주어진 각도의 사인과 코사인은 아래와 같은 함수로 찾을 수 있다.

function printSineAndCosineForAnAngle(angleInDegrees) {
  var angleInRadians = angleInDegrees * Math.PI / 180;
  var s = Math.sin(angleInRadians);
  var c = Math.cos(angleInRadians);
  console.log("s = " + s + " c = " + c);
}

돌리고 싶은 각도의 사인과 코사인으로 rotation을 설정하고 셰이더에 넘겨주면 지오메트리를 원하는 각도로 회전할 수 있다.

  //...
  var angleInRadians = angleInDegrees * Math.PI / 180;
  rotation[0] = Math.sin(angleInRadians);
  rotation[1] = Math.cos(angleInRadians);

 

 

 

 

 

 

https://myoungmin.github.io/WebGL_Fundamentals/

 

WebGL_Fundamentals

WebGL이란? WebGL은 Web Graphics Library의 약자로 웹상에서 2D 및 3D 그래픽을 렌더링하기 위한 로우 레벨 Javascript API.

myoungmin.github.io