MDN self-hosted library · e01.org

Building up a basic demo with Three.js

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

html
<script type="module">
  import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.185.0/three.webgpu.js";
</script>
html
<!doctype html>
<html lang="en-GB">
  <head>
    <meta charset="utf-8" />
    <title>MDN Games: Three.js demo</title>
    <style>
      html,
      body,
      canvas {
        margin: 0;
        padding: 0;
        width: 100%;
        height: 100%;
        font-size: 0;
      }
    </style>
  </head>
  <body>
    <script type="importmap">
      {
        "imports": {
          "three": "https://cdn.jsdelivr.net/npm/three@0.185.0/build/three.webgpu.js",
          "three/webgpu": "https://cdn.jsdelivr.net/npm/three@0.185.0/build/three.webgpu.js"
        }
      }
    </script>
    <script type="module">
      const WIDTH = window.innerWidth;
      const HEIGHT = window.innerHeight;
      /* all our JavaScript code goes here */
    </script>
  </body>
</html>
js
import * as THREE from "three/webgpu";

const renderer = new THREE.WebGPURenderer({ antialias: true });
renderer.setSize(WIDTH, HEIGHT);
renderer.setClearColor(0xdddddd, 1);
document.body.appendChild(renderer.domElement);

await renderer.init();
js
const scene = new THREE.Scene();
js
const camera = new THREE.PerspectiveCamera(70, WIDTH / HEIGHT);
camera.position.z = 50;
scene.add(camera);
js
function render() {
  requestAnimationFrame(render);
  renderer.render(scene, camera);
}
render();
js
const boxGeometry = new THREE.BoxGeometry(10, 10, 10);
js
const basicMaterial = new THREE.MeshBasicMaterial({ color: 0x0095dd });
js
const cube = new THREE.Mesh(boxGeometry, basicMaterial);
js
scene.add(cube);
js
cube.rotation.set(0.4, 0.2, 0);