티스토리 뷰
WebGL이란 무엇인가
웹상에서 그래픽을 사용할때 쓰는 라이브러리다. 자바스크립트를 이용하고 2D, 3D 그래픽을 표현 할 수 있다.
GPU를 이용해 그림을 그려서 성능이 좋다!
API가 lowlevel이다. => 바닥부터 개발을 구현해야한다. 할수 있는것은 많지만, 개발이 오래걸리고 까다롭다.
three.js가 이런 단점을 보완한 라이브러리다.
WebGL 쉽고 간편하게 쓸수 있게 도와주는 라이브러리.
현재 시점에서는 3D에 제일 많이 쓰이고 있다.
게임회사, vr,ar 등등에서 많이 쓰기에 배워두면 좋을것같다!
three.js 사용 방법 3가지
첫번째
1.홈페이지에서 download에서 => three.js를 다운받은 후 해당 파일을 복사한 후 그대로 붙여넣기 작업을 해준다.
2. index.html을 만든 후 아래의 코드를 복사해서 붙여넣기를 한후 <script src="js/three.js"></script> 부분에서 js/부분만 수정해준다.
index.html을 실행시켜보니
아래와같이 움직이고 3D로 돌아가는 상자가 나타난다.
두번째 (three js에서 권장하는 모듈 방식)
모듈을 사용하는 방법
우선 index.html을 만들어준다. 그 이후, hello.js, main.js를 만들어준다.
그안에서 우리는 모듈을 사용할것이다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<!-- <script src="hello.js"></script> -->
<script type="module" src="main.js"></script>
</body>
</html>
type은 모듈이고, src = main.js
export를 사용하여 내보낸다.
export function hello1() {
console.log('hello1 !');
}
export function hello2() {
console.log('hello2 !');
}
main에서 import를 해줘서 받는다.
import { hello1, hello2 } from './hello.js';
hello1();
hello2();
함수가 엄~~청 많은 경우도있는데 이럴때 import를 하는방법은? => * as를 사용해준다.
import * as hello from './hello.js';
hello.hello1();
hello.hello2();
그런데 리액트에서는 export import를 해줄때 중괄호로 안감싼다.
감싸고 안감싸고의 차이는 뭘까?
바로 default의 차이!
export default => 중괄호가 필요없다. (기본값이니까)
export 시? => 중괄호를 쓰게해야한다.
모듈이 먼저 알았으니
이제 three.js를 모듈방식으로 해보자
홈페이지에서 download 받은 three.module.js 를 보자
여기서 index.html 부분 sciprt에 type='module'을 넣어준 후
import * as THREE from './three.module.js';
를 해주면
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>My first three.js app</title>
<style>
body {
margin: 0;
}
</style>
</head>
<body>
<script type="module">
import * as THREE from './three.module.js';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
function animate() {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
세번째 방식 웹팩을 사용하는것
하나하나를 모듈로 보고, 이 모듈을 배포용으로 병합하고 포장하는 작업. 포장하는 작업을 하는애들을 번들러! 라고 한다.
이 번들러중에 웹팩이 가장 인기가많고 많이 사용하는것이다
'Three.js' 카테고리의 다른 글
기초 틀 예시 (0) | 2022.09.21 |
---|---|
transform 변환- 크기 조정 / 회전 (0) | 2022.09.20 |
transform 변환- 위치이동 (1) | 2022.09.19 |
애니메이션 (0) | 2022.09.19 |
three.js 기본요소 익히기 - 기본장면만들기 (0) | 2022.05.27 |