19 kwietnia 2017

Three JS – WebGL

Kategoria: JavaScript Autor: FX

Pierwsza aplikacja 3D

Przykład ze strony WebGL Firefoxa z dodanym sterowaniem klawiatury wygląda tak:

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<!DOCTYPE html>
<html>
<head>
        <meta charset="utf-8">
        <title>MDN Games: Three.js demo</title>
        <style>
                body { margin: 0; padding: 0; }
                canvas { width: 100%; height: 100%; }
        </style>
</head>
<body>
<script src="three.min.js"></script>
<script>
var WIDTH = window.innerWidth-100;
var HEIGHT = window.innerHeight-100;

var renderer = new THREE.WebGLRenderer({antialias:true});
renderer.setSize(WIDTH, HEIGHT);
renderer.setClearColor(0xAAAAAA, 2); //kolor tła
document.body.appendChild(renderer.domElement);

var scene = new THREE.Scene(); //Tworzenie sceny

var camera = new THREE.PerspectiveCamera(70, WIDTH/HEIGHT, 0.1, 10000);
camera.position.z = 50;  
scene.add(camera);

var boxGeometry = new THREE.BoxGeometry(10, 100, 10);
var basicMaterial = new THREE.MeshLambertMaterial({color: 0x0095DD}); //basic
var cube = new THREE.Mesh(boxGeometry, basicMaterial);
cube.position.x = -25;
cube.rotation.set(0.4, 0.2, 0);
scene.add(cube);

var torusGeometry = new THREE.TorusGeometry(17, 5, 10, 12);
var phongMaterial = new THREE.MeshPhongMaterial({color: 0xFF9500});
var torus = new THREE.Mesh(torusGeometry, phongMaterial);
scene.add(torus);

var strangeGeometry = new THREE.DodecahedronGeometry(7);
var lambertMaterial = new THREE.MeshLambertMaterial({color: 0xEAEFF2});
var dodecahedron = new THREE.Mesh(strangeGeometry, lambertMaterial);
dodecahedron.position.x = 25;
scene.add(dodecahedron);

var light = new THREE.PointLight(0xFFFFFF);
light.position.set(-100, 15, 50);
scene.add(light);

//FX
var X_AXIS = new THREE.Vector3( 0, 1, 0 );
       
var t = 0;
function render() {
        t += 0.01;
        requestAnimationFrame(render);
        cube.rotation.y += 0.01;
        torus.rotation.y += 0.01;// Math.abs(Math.sin(t)); //.scale.
        dodecahedron.position.y = -7*Math.sin(t*2);
        renderer.render(scene, camera);
//dziala        camera.rotateOnAxis(X_AXIS,0.01);
}


render();


window.addEventListener('keydown', function(event) {
  switch (event.keyCode) {
    case 37: // Left
      camera.position.x--;
    break;

    case 38: // Up
      camera.position.z--;
    break;

    case 39: // Right
      camera.position.x++;
    break;

    case 40: // Down
      camera.position.z++;
    break;
  }
}, false);



</script>

</body>
</html>

Komentowanie wyłączone.