Skip to content

Instantly share code, notes, and snippets.

@takumifukasawa
Created October 7, 2022 14:47
Show Gist options
  • Save takumifukasawa/4a1debb2bb71661bddfc48c66f039f0f to your computer and use it in GitHub Desktop.
Save takumifukasawa/4a1debb2bb71661bddfc48c66f039f0f to your computer and use it in GitHub Desktop.
threejs sandbox template in single html file.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
name="viewport">
<meta content="ie=edge" http-equiv="X-UA-Compatible">
<title>Document</title>
<style>
.wrapper {
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
}
canvas {
display: block;
position: relative;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div id="js-wrapper" class="wrapper">
<canvas id="js-canvas"></canvas>
</div>
<script src="https://unpkg.com/[email protected]/build/three.min.js"></script>
<script src="https://unpkg.com/[email protected]/examples/js/controls/OrbitControls.js"></script>
<script type="text/javascript">
let width, height;
const wrapperElem = document.getElementById("js-wrapper");
const canvasElem = document.getElementById("js-canvas");
const renderer = new THREE.WebGLRenderer({ canvas: canvasElem });
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(45, 1, 1, 40);
camera.position.copy(new THREE.Vector3(4, 4, 5));
camera.lookAt(new THREE.Vector3(0, 0, 0));
const controls = new THREE.OrbitControls(camera, renderer.domElement);
const cube = new THREE.Mesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshBasicMaterial({ color: 0xff0000 })
);
scene.add(cube);
const gridHelper = new THREE.GridHelper(10, 10);
scene.add(gridHelper);
const onWindowResize = () => {
width = wrapperElem.offsetWidth;
height = wrapperElem.offsetHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
}
const tick = (time) => {
cube.rotation.x = time / 1000 * 0.2;
cube.rotation.y = time / 1000 * 0.4;
cube.rotation.z = time / 1000 * 0.6;
controls.update();
renderer.render(scene, camera);
window.requestAnimationFrame(tick);
}
onWindowResize();
window.addEventListener("resize", onWindowResize);
window.requestAnimationFrame(tick);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment