Skip to content

Instantly share code, notes, and snippets.

@itpastorn
Last active October 18, 2017 13:04
Show Gist options
  • Save itpastorn/60f509d01ef3cfab06584de1bf9e7ea7 to your computer and use it in GitHub Desktop.
Save itpastorn/60f509d01ef3cfab06584de1bf9e7ea7 to your computer and use it in GitHub Desktop.
WebGL Cube
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="UTF-8">
<title>WebGL-kub</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="container"></div>
<script src='https://cdnjs.cloudflare.com/ajax/libs/three.js/r55/three.min.js'></script>
<script src="script.js"></script>
</body>
</html>
/* global THREE */
( () => {
'use strict';
const container = document.getElementById('container');
const scene = new THREE.Scene();
const renderer = new THREE.WebGLRenderer();
container.appendChild(renderer.domElement);
let width, height, aspect, camera;
function setDimensions(resize = true) {
width = container.clientWidth;
height = container.clientHeight;
aspect = width / height;
renderer.setSize(width, height);
if ( resize ) {
camera.aspect = aspect;
camera.updateProjectionMatrix();
} else {
camera = new THREE.PerspectiveCamera(50, aspect, 0.1, 1000);
}
}
setDimensions(false);
window.addEventListener('resize', setDimensions, false);
// Experimentera med siffrorna och värdena här
const geometry = new THREE.CubeGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({
wireframe: true,
color: 0x1111F1
});
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 3;
/**
* Styr positionen på kameran med följande tangenter
* + Zooma in = kameran närmare
* - Zomma ut = kameran längre bort
* Piltangenter för att flytta kameran i x- och y-led
* 0 (nollan) återställer kameran till 0, 0, 3
*
* För att använda funktionen måste användaren
* först klicka i dokumentfönstret så att det får fokus
*/
const zoomKeys = (e) => {
// console.log(e.keyCode);
if ( e.keyCode === 48 ) {
camera.position.z = 3;
camera.position.x = 0;
camera.position.y = 0;
} else if (e.keyCode === 171 ) {
camera.position.z -= 0.2;
camera.position.z = Math.max(camera.position.z, 0.4);
} else if (e.keyCode === 173 ) {
camera.position.z += 0.2;
camera.position.z = Math.min(camera.position.z, 25);
// console.log(camera.position.z);
} else if (e.keyCode === 37 ) {
camera.position.x += 0.2;
} else if (e.keyCode === 39 ) {
camera.position.x -= 0.2;
} else if (e.keyCode === 38 ) {
camera.position.y -= 0.2;
} else if (e.keyCode === 40 ) {
camera.position.y += 0.2;
}
};
document.addEventListener('keydown', zoomKeys, false);
(function render () {
requestAnimationFrame(render);
// Experimentera här med z och andra värden
cube.rotation.x += 0.03;
cube.rotation.y += 0.03;
renderer.render(scene, camera);
})();
})();
* {
margin: 0;
padding: 0;
}
#container {
position: fixed;
width: 100%;
height: 100%;
background-color: #f1f1f1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment