three.interaction

repository·master·Indexed 19 days ago

https://github.com/jasonchen1982/three.interaction.js

A full-interaction event manager for Three.js designed to simplify binding mouse and touch interaction events to 3D objects. It provides an InteractionManager to coordinate events, InteractionLayer for organizing interaction groups, and an Interaction class to define specific logic. Supported events include click, mousedown, mouseup, mousemove, mouseover, mouseout, touchstart, touchend, touchmove, and touchcancel.

Tokens
2.3K
Snippets
11
Records
12
Agent score
65%

What's inside three.interaction

  1. Understand Draco decoder variations

    master

    Draco decoders are provided in two distinct variations depending on your target use case:

    1. Default: Latest stable builds tracking the main Draco master branch. Use these for general 3D mesh/point cloud decompression.
    2. glTF: Builds specifically targeted by the glTF mesh compression extension. Use these when working with glTF assets that utilize Draco compression.
  2. Use event bubbling and stop propagation

    master

    Events in three.interaction bubble up through the display tree. You can listen for events on parent nodes (like the Scene) to catch events triggered by child objects.

    To prevent an event from reaching parent nodes, call ev.stopPropagation() within the event handler.

    // Listen on the scene to catch bubbled events from children
    scene.on('touchstart', ev => {
      console.log('Touch event bubbled to scene:', ev);
    });
    
    // Example of stopping propagation on a specific object
    cube.on('click', ev => {
      console.log('Cube clicked, stopping bubble');
      ev.stopPropagation();
    });
  3. Initialize the Interaction manager

    master

    To use three.interaction, create a new instance of the Interaction class. You must provide the WebGLRenderer, the Scene, and the PerspectiveCamera used in your Three.js setup. Once initialized, the manager enables event binding for your 3D objects.

    import { Scene, PerspectiveCamera, WebGLRenderer } from 'three';
    import { Interaction } from 'three.interaction';
    
    const renderer = new WebGLRenderer({ canvas: canvasElement });
    const scene = new Scene();
    const camera = new PerspectiveCamera(60, width / height, 0.1, 100);
    
    // Initialize the interaction manager
    const interaction = new Interaction(renderer, scene, camera);
  4. Install three.js

    master

    You can include three.js in your project using one of the following methods:

    1. Direct Script Tag: Download the minified library (three.min.js) and include it in your HTML.
    2. ES Modules: Install and import it as a module via npm or other module loaders.
    3. Manual Build: Build the library yourself following the build instructions in the official wiki.
    <script src="js/three.min.js"></script>
  5. Configure THREE.DRACOLoader with Draco decoders

    master

    To use Draco compression in a Three.js project, you must provide the path to the Draco decoder files and optionally configure the decoder type. The decoder files can be the default builds or glTF-specific builds.

    Available files in the decoder directory typically include:

    • draco_decoder.js: Emscripten-compiled decoder (compatible with all modern browsers).
    • draco_decoder.wasm: WebAssembly decoder (compatible with newer browsers/devices).
    • draco_wasm_wrapper.js: JavaScript wrapper for the WASM decoder.

    Use setDecoderPath to point to the directory containing these files and setDecoderConfig if you need to manually override WASM support detection.

    // 1. Set the path to the folder containing the decoder files
    THREE.DRACOLoader.setDecoderPath('path/to/decoders/');
    
    // 2. (Optional) Override detection of WASM support
    // Use {type: 'js'} to force the JS decoder if WASM is not desired
    THREE.DRACOLoader.setDecoderConfig({type: 'js'});
    
    // 3. Initialize the loader
    var dracoLoader = new THREE.DRACOLoader();
  6. Generate typeface.json fonts using Facetype.js

    master

    To use custom fonts in Three.js (specifically for TextGeometry), you must convert font files into the typeface.json format. You can use Facetype.js to perform this conversion.

    1. Visit the Facetype.js website: http://gero3.github.io/facetype.js/
    2. Upload your font file (e.g., .ttf).
    3. Download the resulting .json file.
    4. Use this JSON file with the FontLoader in your Three.js project.
    http://gero3.github.io/facetype.js/
  7. Basic usage of three.js to render a 3D scene

    master

    To render a basic 3D scene, you need to initialize a camera, a scene, a geometry/material combination (a mesh), and a renderer. The renderer's domElement is then appended to the document to display the viewport. An animation loop using requestAnimationFrame is used to update object properties (like rotation) and re-render the scene continuously.

    var camera, scene, renderer;
    var geometry, material, mesh;
    
    init();
    animate();
    
    function init() {
    	camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 10 );
    	camera.position.z = 1;
    
    	scene = new THREE.Scene();
    
    	geometry = new THREE.BoxGeometry( 0.2, 0.2, 0.2 );
    	material = new THREE.MeshNormalMaterial();
    
    	mesh = new THREE.Mesh( geometry, material );
    	scene.add( mesh );
    
    	renderer = new THREE.WebGLRenderer( { antialias: true } );
    	renderer.setSize( window.innerWidth, window.innerHeight );
    	document.body.appendChild( renderer.domElement );
    
    }
    
    function animate() {
    	requestAnimationFrame( animate );
    
    	mesh.rotation.x += 0.01;
    	mesh.rotation.y += 0.02;
    
    	renderer.render( scene, camera );
    }
  8. Handle interaction events on Three.js objects

    master

    You can attach event listeners directly to Three.js objects (like Mesh) using the .on(eventName, callback) method.

    To change the cursor style when hovering over an object, set the .cursor property on that object.

    Supported event names include:

    • Mouse events: click, mousedown, mouseup, mousemove, mouseover, mouseout
    • Touch events: touchstart, touchend, touchmove, touchcancel
    const cube = new Mesh(
      new BoxGeometry(1, 1, 1),
      new MeshBasicMaterial({ color: 0xffffff }),
    );
    scene.add(cube);
    
    // Set cursor style
    cube.cursor = 'pointer';
    
    // Attach event listeners
    cube.on('click', function(ev) {
      console.log('Cube clicked');
    });
    
    cube.on('mousemove', function(ev) {
      // Handle mouse movement
    });
  9. Use InteractionManager to manage 3D interaction events

    master

    The InteractionManager is the primary entrypoint for managing 3D interaction events within a Three.js scene. It coordinates how interactions are processed and distributed across different layers.

    import { InteractionManager } from 'three.interaction';
    
    // Initialize the manager (usage depends on internal implementation)
    const manager = new InteractionManager();
  10. Use InteractionLayer to organize interaction groups

    master

    The InteractionLayer allows you to group specific objects or sets of interactions together. This is useful for managing different interaction contexts (e.g., UI vs. World objects) within the same scene.

    import { InteractionLayer } from 'three.interaction';
    
    const layer = new InteractionLayer();
  11. Use Interaction to define specific interaction logic

    master

    The Interaction class represents a specific interaction instance or definition, allowing you to define how specific events (like clicks or drags) behave on 3D objects.

    import { Interaction } from 'three.interaction';
    
    const interaction = new Interaction();