Tech Tips

  1. Uncategorized
  2. 93 view

[Javascript]Three.js trial

Three.js allows us to draw 3D CG on browser.
threejs.org I’ll draw cube using it.
Reference page is here. First is download.
I’ll use three.min.js in build directory.
Download
1
git clone https://github.com/mrdoob/three.js.git
Next is html file.
Three.js seems to make canvas element.
html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html>
        <head>
                <title>Cube</title>
                <!-- three.js library -->
                <script src="./three.min.js" type="text/javascript"></script>
                <!-- main processing part -->
                <script src="./main.js" type="text/javascript"></script>
        </head>
        <body>
                <!-- Cube will be drawn here -->
                <div id="canvas"></div>
        </body>
</html>
Next is main.js.
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
window.onload = function() {
        // Canvas size
        var width = 640;
        var height = 480;
 
        // Cube Size
        var geometry = new THREE.CubeGeometry(100, 100, 100);
        // Cube Material Info(not metal)
        var material = new THREE.MeshLambertMaterial({color: 0x0000aa});
        // Create Cube
        var mesh = new THREE.Mesh(geometry, material);
        // Rotate Cube
        mesh.rotation = {x: 0.5, y: 0.5, z: 0.0};
 
        // Setting Camera
        var camera = new THREE.PerspectiveCamera(40, width / height, 1, 1000);
        // Camera Position
        camera.position.z = -400;
        // Camera Angle
        camera.lookAt(mesh.position);
 
        // Create Space
        var scene = new THREE.Scene();
        // Add cube to Space
        scene.add(mesh);
 
        // Create Light element
        var light    = new THREE.DirectionalLight(0xffffff, 1.5);
        // Light element position
        light.position = {x: 0, y: 0.2, z: -1};
        // Add light element to the space
        scene.add(light);
 
        // Create renderer
        var renderer = new THREE.WebGLRenderer();
        // Set canvas size
        renderer.setSize(width, height);
 
        // Set canvas to div element
        document.getElementById('canvas').appendChild(renderer.domElement);
        renderer.render(scene, camera);
}
Result is like this.
Easy to write 🙂
Demo

Uncategorized recent post

  1. Run Amazon FreeRTOS on M5Stack Core2 for AWS …

  2. Udacity Self-Driving Car Engineer Nanodegree …

  3. Install sbt 1.0.0 and run sample template

  4. Visualization of Neural Network and its Train…

  5. [Machine Learning]Created docker image includ…

関連記事

PAGE TOP