threejs-loops/index.html
2021-04-15 18:39:00 -04:00

81 lines
2.2 KiB
HTML

<script>
function loop(inFunc, inDelay)
{
var output;
output = {
timeOld:0,
timeNew:0,
run:false,
delay:inDelay,
func:inFunc,
loop: () =>
{
if(!output.run){ return; }
output.timeOld = output.timeNew;
output.timeNew = new Date();
output.func(output.timeOld, output.timeNew);
setTimeout(output.loop, output.delay);
},
start: () =>
{
if(output.run){ return; }
output.run = true;
output.timeOld = output.timeNew = new Date();
output.loop();
},
stop: () => output.run = false,
toggle: () => output.run ? output.stop() : output.start()
};
return output;
}
</script>
<script type="module">
import * as THREE from 'https://unpkg.com/three@0.127.0/build/three.module.js';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const cube = new THREE.Mesh( geometry, material );
const renderer = new THREE.WebGLRenderer();
renderer.domElement.style.width = "100%";
renderer.domElement.style.height = "100%";
renderer.domElement.style.display = "block";
document.body.appendChild( renderer.domElement );
scene.add( cube );
camera.position.z = 5;
let render = inTime =>
{
renderer.render( scene, camera );
};
let update = (inTimeOld, inTimeNew) =>
{
let delta = (inTimeNew - inTimeOld)*0.001;
cube.rotation.x += delta;
};
let resize = () =>
{
let w = renderer.domElement.clientWidth, h = renderer.domElement.clientHeight
camera.aspect = w/h ;
camera.updateProjectionMatrix();
renderer.setSize(w, h, false);
};
window.addEventListener("resize", resize);
resize();
let updateLoop = loop(update, 10);
let renderLoop = loop(render, 50);
updateLoop.start();
renderLoop.start();
</script>