Getting Started with Three.js

Please note: this has been tested with Three.js r82

 

sample.zip

I have used Three.js for some of my experiments, and it does a really great job of abstracting away the headaches of getting going with 3D in the browser. With it you can create cameras, objects, lights, materials and more, and you have a choice of renderer, which means you can decide if you want your scene to be drawn using HTML 5’s canvas, WebGL or SVG. And since it’s open source you could even get involved with the project. But right now I’ll focus on what I’ve learned by playing with it as an engine, and talk you through some of the basics.

For all the awesomeness of Three.js, there can be times where you might struggle. Typically you will need to spend quite a large amount of time with the examples, reverse engineering and (in my case certainly) hunting down specific functionality and occasionally asking questions via GitHub. If you have to ask questions, by the way, you should do that on Stack Overflow!

The basics

I will assume that you have at least a passing knowledge of 3D, and reasonable proficiency with JavaScript. If you don’t it may be worth learning a bit before you try and play with this stuff, as it can get a little confusing.

In our 3D world we will have some of the following, which I will guide you through the process of creating:

  1. A scene
  2. A renderer
  3. A camera
  4. An object or two (with materials)

You can, of course, do some crazy things, and my hope is that you will go on to do that and start to experiment with 3D in your browser.

Support

WebGL support is really awesome nowadays: Chrome, Firefox, Safari, Internet Explorer and Edge all support WebGL. So there’s little reason to not use it!

Set the Scene

I’ll assume you’ve chosen a browser that supports all the rendering technologies, and that you want to render with Canvas or WebGL, since they’re the more standard choices. Canvas is more widely supported than WebGL, but it’s worth noting that WebGL runs on your graphics card’s GPU, which means that your CPU can concentrate on other non-rendering tasks like any physics or user interaction you’re trying to do.

Irrespective of your chosen renderer you should bear in mind that the JavaScript will need to optimised for performance. 3D isn’t a lightweight task for a browser (and it’s awesome that it’s even possible), so be careful to understand where any bottlenecks are in your code, and remove them if you can!

So with that said, and on the assumption you have downloaded and included three.js in your HTML file, how do you go about setting up a scene? Like this:

 

// Set the scene size.
const WIDTH = 400;
const HEIGHT = 300;

// Set some camera attributes.
const VIEW_ANGLE = 45;
const ASPECT = WIDTH / HEIGHT;
const NEAR = 0.1;
const FAR = 10000;

// Get the DOM element to attach to
const container =
    document.querySelector('#container');

// Create a WebGL renderer, camera
// and a scene
const renderer = new THREE.WebGLRenderer();
const camera =
    new THREE.PerspectiveCamera(
        VIEW_ANGLE,
        ASPECT,
        NEAR,
        FAR
    );

const scene = new THREE.Scene();

// Add the camera to the scene.
scene.add(camera);

// Start the renderer.
renderer.setSize(WIDTH, HEIGHT);

// Attach the renderer-supplied
// DOM element.
container.appendChild(renderer.domElement);

Not too tricky, really!

Making a Mesh

So we have a scene, a camera and a renderer (I opted for a WebGL one in my sample code) but we have nothing to actually draw. Three.js actually comes with support for loading a few different standard file types, which is great if you are outputting models from Blender, Maya, Cinema4D or anything else. To keep things simple (this is about getting started after all!) I’ll talk about primitives. Primitives are geometric meshes, relatively basic ones like Spheres, Planes, Cubes and Cylinders. Three.js lets you create these types of primitives easily:

 

// Set up the sphere vars
const RADIUS = 50;
const SEGMENTS = 16;
const RINGS = 16;

// Create a new mesh with
// sphere geometry - we will cover
// the sphereMaterial next!
const sphere = new THREE.Mesh(

  new THREE.SphereGeometry(
    RADIUS,
    SEGMENTS,
    RINGS),

  sphereMaterial);

// Move the Sphere back in Z so we
// can see it.
sphere.position.z = -300;

// Finally, add the sphere to the scene.
scene.add(sphere);

All good, but what about the material for the sphere? In the code we’ve used a variable sphereMaterial but we’ve not defined it yet. First we need to talk about materials in a bit more detail.

Materials

Without doubt this is one of the most useful parts of Three.js. It provides for you a number of common (and very handy) materials to apply to your meshes:

  1. Basic, which just means that it renders ‘unlit’.
  2. Lambert.
  3. Phong.

There are more, but again in the interests of simplicity I’ll let you discover those for yourself. In the case of WebGL particularly these materials can be a life-saver. Why? Well because in WebGL you have to write shaders for everything being rendered. Shaders are a huge topic in themselves, but in short they are written in GLSL (OpenGL Shader Language), which tells the GPU how something should look. This means you need to mimic the maths of lighting, reflection and so on. It can get very complicated very quickly. Thanks to Three.js you don’t have to do this if you don’t want to because it abstracts that away for you. If you want to write shaders, however, you can do that too with a MeshShaderMaterial, so it’s a flexible setup.

For now, however, let’s apply a lambert material to the sphere:

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

 

// create the sphere's material
const sphereMaterial =
  new THREE.MeshLambertMaterial(
    {
      color: 0xCC0000
    });

It’s worth pointing out as well that there are other properties you can specify when you create a material besides the colour, such as smoothing or environment maps. You should check out the docs for the various properties you can set on the materials and, in fact, any object that the engine provides for you.

Lights!

If you were to render the scene right now you’d see a red circle. Even though we have a Lambert material applied there’s no light in the scene so by default Three.js will revert to a full ambient light, which is the same as flat colouring. Let’s fix that with a simple point of light:

 

// create a point light
const pointLight =
  new THREE.PointLight(0xFFFFFF);

// set its position
pointLight.position.x = 10;
pointLight.position.y = 50;
pointLight.position.z = 130;

// add to the scene
scene.add(pointLight);

## Render Loop

We now actually have everything set up to render, remarkably. But we actually need to go ahead and do just that:

 

// Draw!
renderer.render(scene, camera);

You’re probably going to want to render more than once, though, so if you’re going to do a loop you should really use requestAnimationFrame; it’s by far the smartest way of handling animation in the browser. That render call above just needs wrapping, like this:

function update () {
  // Draw!
  renderer.render(scene, camera);

  // Schedule the next frame.
  requestAnimationFrame(update);
}

// Schedule the first frame.
requestAnimationFrame(update);

And we’re good.

Common Object Properties

If you take time to look through the code for Three.js you’ll see a lot of objects “inherit” from Object3D. This is a base object which contains some very useful properties, such as the position, rotation and scale information. In particular our Sphere is a Mesh which inherits from Object3D, to which it adds its own properties: geometry and materials. Why do I mention these? Well it’s unlikely you’re going to want to just have a sphere on your screen that does nothing, and these properties are worth investigating as they allow you to manipulate the underlying details of the meshes and materials on the fly.

// sphere geometry
sphere.geometry

// which contains the vertices and faces
sphere.geometry.vertices // an array
sphere.geometry.faces // also an array

// its position
sphere.position // contains x, y and z
sphere.rotation // same
sphere.scale // ... same

Dirty Little Secrets

I just wanted to quickly point out a quick gotcha for Three.js, which is that if you modify, for example, the vertices of a mesh, you will notice in your render loop that nothing changes. Why? Well because Three.js (as far as I can tell) caches the data for a mesh as something of an optimisation. What you actually need to do is to flag to Three.js that something has changed so it can recalculate whatever it needs to. You do this with the following:

 

// Changes to the vertices
sphere.geometry.verticesNeedUpdate = true;

// Changes to the normals
sphere.geometry.normalsNeedUpdate = true;

Again there are more, but those two I’ve found are the most useful. You should obviously only flag the things that have changed to avoid unnecessary calculations.

Conclusion

Well I hope you’ve found this brief introduction to Three.js helpful. There’s nothing quite like actually getting your hands dirty and trying something, and I can’t recommend it highly enough. 3D running natively in the browser is a lot of fun, and using an engine like Three.js takes away a lot of the headaches for you and lets you get to making some seriously cool stuff.

To help you out a bit I’ve wrapped up the source code in this lab article, so you can use that as a reference.

sample.zip

[출처] https://aerotwist.com/tutorials/getting-started-with-three-js/

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
34 JavaScript 강좌 | 배열(Array) > 선언하기 file 졸리운_곰 2017.05.31 294
33 JSON javascript 읽기 졸리운_곰 2017.05.31 525
32 HOW TO PUT TEXT BOXES IN AN HTML5 FORM file 졸리운_곰 2017.05.30 449
31 HTML div 왼쪽, 오른쪽 분할 졸리운_곰 2017.05.30 438
30 자바스크립트와 Node.js를 이용한 웹 크롤링 테크닉 file 졸리운_곰 2017.05.27 570
29 JSON - 자바스크립트 강좌 JS / CSE file 졸리운_곰 2017.05.06 500
28 Javascript JSON.parse(), JSON.stringify() 사용하는법 졸리운_곰 2017.05.06 492
27 JSON Text를 JSON Object로 변환하기 졸리운_곰 2017.05.06 478
26 Three.js로 AutoCad DXF 모델 출력 : Three-Dxf file 졸리운_곰 2017.04.27 912
25 three.js r84 다운로드 file 졸리운_곰 2017.04.15 393
24 jqPlot으로 그래프 그리기! file 졸리운_곰 2017.03.20 682
23 XPath 이야기 file 졸리운_곰 2017.03.20 591
22 HTML : 폼(form) 이해 file 졸리운_곰 2017.03.20 401
21 [JavaScript] 공백(빈공간) 문자 제거하기, 없애기, 정규표현식 사용 졸리운_곰 2017.01.22 522
20 폼(Form) 요소 #2 - LABEL, INPUT file 졸리운_곰 2017.01.22 467
19 [jQuery] Ajax의 흐름과 예제 졸리운_곰 2017.01.17 632
18 basic plot graph by javascript, 자바스크립트로 그래프그리기 초간단 졸리운_곰 2015.11.13 574
17 A Survey of the JavaScript Programming Language file 졸리운_곰 2015.11.12 665
16 SVG by HTML5 file 졸리운_곰 2015.11.12 463
15 JavaScript Canvas examples 졸리운_곰 2015.11.10 360
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED