### Basic Usage of three.interaction.js with Three.js Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/docs/index.html This example illustrates the fundamental setup and usage of three.interaction.js within a Three.js application. It shows how to initialize the Interaction manager with a renderer, scene, and camera, and then attach various interaction events (click, touch, mouse events) to a 3D object (cube) and the scene itself. Events bubble up the display tree, and can be stopped using `ev.stopPropagation()`. ```javascript import { Scene, PerspectiveCamera, WebGLRenderer, Mesh, BoxGeometry, MeshBasicMaterial } 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); // new a interaction, then you can add interaction-event with your free style const interaction = new Interaction(renderer, scene, camera); const cube = new Mesh( new BoxGeometry(1, 1, 1), new MeshBasicMaterial({ color: 0xffffff }) ); scene.add(cube); cube.cursor = 'pointer'; cube.on('click', function(ev) {}); cube.on('touchstart', function(ev) {}); cube.on('touchcancel', function(ev) {}); cube.on('touchmove', function(ev) {}); cube.on('touchend', function(ev) {}); cube.on('mousedown', function(ev) {}); cube.on('mouseout', function(ev) {}); cube.on('mouseover', function(ev) {}); cube.on('mousemove', function(ev) {}); cube.on('mouseup', function(ev) {}); // and so on ... /** * you can also listen on parent-node or any display-tree node, * source event will bubble up along with display-tree. * you can stop the bubble-up by invoke ev.stopPropagation function. */ scene.on('touchstart', ev => { console.log(ev); }) scene.on('touchmove', ev => {}); ``` -------------------------------- ### Install three.interaction.js via npm Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/docs/index.html This snippet demonstrates how to install the three.interaction.js library using npm, the Node.js package manager. The '-S' flag ensures the package is saved as a production dependency in your project's package.json file. ```bash npm install -S three.interaction ``` -------------------------------- ### Install three.interaction via npm Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/README.md Instructions to install the `three.interaction` library using the npm package manager. ```sh npm install -S three.interaction ``` -------------------------------- ### Include Three.js Library in HTML Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/examples/libs/three/README.md This snippet demonstrates how to include the Three.js library in an HTML document using a script tag. It assumes the `three.min.js` file is located in a `js` directory relative to the HTML file. This is a common way to get started with Three.js in web projects. ```html ``` -------------------------------- ### Configure Documentation Site and Google Analytics Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/docs/index.html This JavaScript snippet initializes a configuration object for a documentation site, specifying details like application name, copyright, and Google Analytics ID. It then sets up Google Analytics tracking to record page views. ```javascript var config = {"monospaceLinks":false,"cleverLinks":false,"default":{"outputSourceFiles":true},"applicationName":"three.interaction.js","footer":"Made with ♥ by JasonChen (github.com/jasonChen1982)","copyright":"three.interaction.js Copyright © 2013-2017 JasonChen.","disqus":"","googleAnalytics":"UA-103772589-5","openGraph":{"title":"","type":"website","image":"","site_name":"","url":""},"meta":{"title":"three.interaction.js API Documentation","description":"Documentation for three.interaction.js library","keyword":"docs, documentation, three.js, three.js event system, three.interaction.js, renderer, html5, javascript, jsdoc"},"linenums":true}; var _gaq = _gaq || []; _gaq.push(['_setAccount', config.googleAnalytics]); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); ``` -------------------------------- ### Ticker Methods: start, stop Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/docs/Ticker.html Documents the `start` and `stop` methods for controlling a tick loop. `start` initiates the loop, while `stop` halts it. ```APIDOC start () - Description: start tick loop stop () - Description: stop tick loop ``` -------------------------------- ### Configure Google Analytics and Documentation Metadata Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/docs/patch_Object3D.js.html This JavaScript snippet initializes a configuration object for the documentation site, including application name, copyright, footer, and meta tags. It also sets up Google Analytics tracking for page views using the classic `_gaq` syntax. ```javascript var config = {"monospaceLinks":false,"cleverLinks":false,"default":{"outputSourceFiles":true},"applicationName":"three.interaction.js","footer":"Made with ♥ by JasonChen (github.com/jasonChen1982)","copyright":"three.interaction.js Copyright © 2013-2017 JasonChen.","disqus":"","googleAnalytics":"UA-103772589-5","openGraph":{"title":"","type":"website","image":"","site_name":"","url":""},"meta":{"title":"three.interaction.js API Documentation","description":"Documentation for three.interaction.js library","keyword":"docs, documentation, three.js, three.js event system, three.interaction.js, renderer, html5, javascript, jsdoc"},"linenums":true}; var _gaq = _gaq || []; _gaq.push(['_setAccount', config.googleAnalytics]); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); ``` -------------------------------- ### Three.js Interaction Event Binding Example Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/docs/Interaction.html Demonstrates how to initialize the `Interaction` class and bind various interaction events (touchstart, mousedown, pointerdown) to a Three.js Mesh and the Scene. It illustrates how events bubble up the display tree and how to stop propagation using `ev.stopPropagation()`. ```JavaScript import { Scene, PerspectiveCamera, WebGLRenderer, Mesh, BoxGeometry, MeshBasicMaterial } 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); const interaction = new Interaction(renderer, scene, camera); // then you can bind every interaction event with any mesh which you had `add` into `scene` before const cube = new Mesh( new BoxGeometry(1, 1, 1), new MeshBasicMaterial({ color: 0xffffff }), ); scene.add(cube); cube.on('touchstart', ev => { console.log(ev); }); cube.on('mousedown', ev => { console.log(ev); }); cube.on('pointerdown', ev => { console.log(ev); }); // and so on ... // you can also listen on parent-node or any display-tree node, // source event will bubble up along with display-tree. // you can stop the bubble-up by invoke ev.stopPropagation function. scene.on('touchstart', ev => { console.log(ev); }) ``` -------------------------------- ### APIDOC: Utils Module Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/docs/index.html The `Utils` module provides helper functions for common checks within the three.interaction.js library. These methods are typically used internally or for quick type verification. ```APIDOC Utils: isFunction(value: any): boolean - Checks if the given value is a function. - Parameters: - value: The value to check. - Returns: True if the value is a function, false otherwise. isUndefined(value: any): boolean - Checks if the given value is undefined. - Parameters: - value: The value to check. - Returns: True if the value is undefined, false otherwise. ``` -------------------------------- ### Utils Module API Reference Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/docs/patch_Object3D.js.html Provides utility functions for type checking within the three.interaction.js library. ```APIDOC Utils: Methods: isFunction(value): Checks if a value is a function. isUndefined(value): Checks if a value is undefined. ``` -------------------------------- ### InteractionData Module API Reference Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/docs/utils_Utils.js.html API documentation for the `InteractionData` module, which encapsulates detailed information about an interaction event. This includes properties related to pointer input, such as button states, global coordinates, and pressure, providing comprehensive context for handling user interactions. ```APIDOC InteractionData: Members: button: number - The button number that was pressed (e.g., 0 for left, 1 for middle, 2 for right). buttons: number - A bitmask indicating which buttons are currently pressed. global: THREE.Vector2 - The global coordinates of the pointer event. height: number - The height of the contact geometry (for touch/pointer events). identifier: number - A unique ID for the pointer (for touch/pointer events). isPrimary: boolean - Indicates if this is the primary pointer for a multi-pointer interaction. originalEvent: Event - The original DOM event that triggered the interaction. pointerId: number - The unique ID of the pointer (for pointer events). pointerType: string - The type of pointer (e.g., 'mouse', 'touch', 'pen'). pressure: number - The normalized pressure of the pointer input (0 to 1). rotationAngle: number - The angle of rotation of the contact geometry (for touch/pointer events). tangentialPressure: number - The normalized tangential pressure of the pointer input. target: THREE.Object3D - The Three.js object that was targeted by the interaction. tiltX: number - The tilt of the pointer along the X-axis (for pen input). tiltY: number - The tilt of the pointer along the Y-axis (for pen input). twist: number - The twist of the pointer (for pen input). width: number - The width of the contact geometry (for touch/pointer events). ``` -------------------------------- ### Configure Documentation and Google Analytics Tracking Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/docs/interaction_InteractionData.js.html This JavaScript snippet initializes a configuration object for a documentation generator, setting properties like application name, copyright, and Google Analytics ID. It then sets up Google Analytics tracking to record page views using the classic ga.js library. ```javascript var config = {"monospaceLinks":false,"cleverLinks":false,"default":{"outputSourceFiles":true},"applicationName":"three.interaction.js","footer":"Made with ♥ by JasonChen (github.com/jasonChen1982)","copyright":"three.interaction.js Copyright © 2013-2017 JasonChen.","disqus":"","googleAnalytics":"UA-103772589-5","openGraph":{"title":"","type":"website","image":"","site_name":"","url":""},"meta":{"title":"three.interaction.js API Documentation","description":"Documentation for three.interaction.js library","keyword":"docs, documentation, three.js, three.js event system, three.interaction.js, renderer, html5, javascript, jsdoc"},"linenums":true}; var _gaq = _gaq || []; _gaq.push(['_setAccount', config.googleAnalytics]); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); ``` -------------------------------- ### Documentation Site Configuration and Google Analytics Setup Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/docs/utils_Ticker.js.html This JavaScript code defines a configuration object for the three.interaction.js documentation site, including application name, footer, copyright, and meta tags. It also initializes Google Analytics tracking by setting the account ID and pushing a pageview event, dynamically loading the Google Analytics script. ```javascript var config = {"monospaceLinks":false,"cleverLinks":false,"default":{"outputSourceFiles":true},"applicationName":"three.interaction.js","footer":"Made with ♥ by JasonChen (github.com/jasonChen1982)","copyright":"three.interaction.js Copyright © 2013-2017 JasonChen.","disqus":"","googleAnalytics":"UA-103772589-5","openGraph":{"title":"","type":"website","image":"","site_name":"","url":""},"meta":{"title":"three.interaction.js API Documentation","description":"Documentation for three.interaction.js library","keyword":"docs, documentation, three.js, three.js event system, three.interaction.js, renderer, html5, javascript, jsdoc"},"linenums":true}; var _gaq = _gaq || []; _gaq.push(['_setAccount', config.googleAnalytics]); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); ``` -------------------------------- ### Ticker Module API Reference Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/docs/utils_Utils.js.html API documentation for the `Ticker` module, which provides a mechanism for managing and dispatching events on a regular interval, typically used for animation loops or continuous updates. It offers methods for event registration and controlling the ticker's lifecycle. ```APIDOC Ticker: Methods: emit(eventName: string, ...args: any[]): void - Emits a custom event with optional arguments. off(eventName: string, listener: Function): void - Removes an event listener for a specific event. on(eventName: string, listener: Function): void - Registers an event listener for a specific event. once(eventName: string, listener: Function): void - Registers an event listener that will be invoked at most once. start(): void - Starts the ticker, beginning the dispatch of events. stop(): void - Stops the ticker, pausing the dispatch of events. ``` -------------------------------- ### Interaction Module API Reference Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/docs/utils_Utils.js.html Detailed API documentation for the `Interaction` module, which manages interactive behaviors within a Three.js scene. It lists various members that control interaction properties and methods for handling events, hit testing, and cursor management. ```APIDOC Interaction: Members: autoPreventDefault: boolean - Whether to automatically call `preventDefault` on DOM events. camera: THREE.Camera - The camera used for raycasting. currentCursorMode: string - The current cursor style mode. cursorStyles: object - An object mapping cursor modes to CSS cursor styles. eventData: object - Data related to the current interaction event. interactionFrequency: number - The frequency (in milliseconds) at which interaction events are processed. mouse: THREE.Vector2 - The current mouse position in normalized device coordinates. moveWhenInside: boolean - Whether to trigger 'mousemove' events when the pointer is inside an object. renderer: THREE.WebGLRenderer - The WebGL renderer instance. scene: THREE.Scene - The Three.js scene being interacted with. supportsPointerEvents: boolean - Indicates if the browser supports Pointer Events. supportsTouchEvents: boolean - Indicates if the browser supports Touch Events. Methods: destroy(): void - Cleans up all event listeners and resources used by the interaction instance. emit(eventName: string, ...args: any[]): void - Emits a custom event with optional arguments. hitTest(object: THREE.Object3D, raycaster: THREE.Raycaster): THREE.Intersection[] - Performs a raycast against a specific object to find intersections. mapPositionToPoint(position: THREE.Vector2): THREE.Vector2 - Maps a screen position (e.g., mouse coordinates) to normalized device coordinates. off(eventName: string, listener: Function): void - Removes an event listener for a specific event. on(eventName: string, listener: Function): void - Registers an event listener for a specific event. once(eventName: string, listener: Function): void - Registers an event listener that will be invoked at most once. setCursorMode(mode: string): void - Sets the cursor style based on a predefined mode. setTargetElement(element: HTMLElement): void - Sets the DOM element that interaction events will be listened on. ``` -------------------------------- ### Utils API Reference Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/docs/global.html Documentation for utility methods provided by the three.interaction.js library, including type checking functions and a method to get the variable type. ```APIDOC Utils: isFunction() - Checks if a variable is a function. isUndefined() - Checks if a variable is undefined. _rt(val: *) - Description: Get variable type. - Parameters: - val: A variable which you want to get the type. - Returns: String ``` -------------------------------- ### Configure Documentation Page and Google Analytics Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/docs/patch_EventDispatcher.js.html This JavaScript snippet defines a configuration object for a documentation site, specifying application details, copyright, and metadata. It also initializes Google Analytics tracking to monitor page views, using the configured Google Analytics ID. ```javascript var config = {"monospaceLinks":false,"cleverLinks":false,"default":{"outputSourceFiles":true},"applicationName":"three.interaction.js","footer":"Made with ♥ by JasonChen (github.com/jasonChen1982)","copyright":"three.interaction.js Copyright © 2013-2017 JasonChen.","disqus":"","googleAnalytics":"UA-103772589-5","openGraph":{"title":"","type":"website","image":"","site_name":"","url":""},"meta":{"title":"three.interaction.js API Documentation","description":"Documentation for three.interaction.js library","keyword":"docs, documentation, three.js, three.js event system, three.interaction.js, renderer, html5, javascript, jsdoc"},"linenums":true}; var _gaq = _gaq || []; _gaq.push(['_setAccount', config.googleAnalytics]); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); ``` -------------------------------- ### Configure three.interaction.js and Google Analytics Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/docs/InteractionData.html Initializes the configuration for the three.interaction.js documentation application, including metadata, application name, copyright, and Google Analytics tracking. This setup is typically used for documentation generation or web analytics integration. ```javascript var config = {"monospaceLinks":false,"cleverLinks":false,"default":{"outputSourceFiles":true},"applicationName":"three.interaction.js","footer":"Made with ♥ by JasonChen (github.com/jasonChen1982)","copyright":"three.interaction.js Copyright © 2013-2017 JasonChen.","disqus":"","googleAnalytics":"UA-103772589-5","openGraph":{"title":"","type":"website","image":"","site_name":"","url":""},"meta":{"title":"three.interaction.js API Documentation","description":"Documentation for three.interaction.js library","keyword":"docs, documentation, three.js, three.js event system, three.interaction.js, renderer, html5, javascript, jsdoc"},"linenums":true}; var _gaq = _gaq || []; _gaq.push(['_setAccount', config.googleAnalytics]); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); ``` -------------------------------- ### Call prettyPrint Function in JavaScript Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/docs/index.html Illustrates a simple JavaScript function call to `prettyPrint()`. This function is commonly used to format or display data in a more readable, 'pretty' format, often for debugging or presentation. ```javascript prettyPrint(); ``` -------------------------------- ### InteractionEvent Module API Reference Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/docs/utils_Utils.js.html API documentation for the `InteractionEvent` module, representing an event that occurs during user interaction with Three.js objects. It includes properties like the current target, associated interaction data, and methods to control event propagation. ```APIDOC InteractionEvent: Members: currentTarget: THREE.Object3D - The current object that the event is bubbling through. data: InteractionData - The `InteractionData` object associated with this event. intersects: THREE.Intersection[] - An array of intersected objects from the raycast. stopped: boolean - Indicates if event propagation has been stopped. target: THREE.Object3D - The original object that the event was dispatched on. type: string - The type of the interaction event (e.g., 'click', 'mouseover'). Methods: stopPropagation(): void - Stops the propagation of the current event through the scene graph. ``` -------------------------------- ### Extend THREE.Object3D for Interaction Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/docs/patch_Object3D.js.html This JavaScript code extends the `THREE.Object3D` prototype with properties and a method necessary for interaction detection and management within the `three.interaction.js` library. It adds flags for interactivity and a custom raycasting test. ```JavaScript import { Object3D } from 'three'; /** * whether displayObject is interactively */ Object3D.prototype.interactive = false; /** * whether displayObject's children is interactively */ Object3D.prototype.interactiveChildren = true; /** * whether displayObject had touchstart * @private */ Object3D.prototype.started = false; /** * tracked event cache, like: touchend、mouseout、pointerout which decided by primary-event */ Object.defineProperty(Object3D.prototype, 'trackedPointers', { get() { if (!this._trackedPointers) this._trackedPointers = {}; return this._trackedPointers; }, }); /** * dispatch a raycast * * @param {Raycaster} raycaster Raycaster object, get from THREE.Raycaster * @return {Object|Boolean} had pass hit-test */ Object3D.prototype.raycastTest = function(raycaster) { const result = []; this.raycast(raycaster, result); if (result.length > 0) { return result[0]; } return false; }; ``` -------------------------------- ### Google Analytics Page Tracking Setup Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/docs/interaction_InteractionLayer.js.html This JavaScript code snippet initializes Google Analytics tracking for the documentation page. It sets the Google Analytics account ID, tracks page views, and dynamically loads the Google Analytics script from either HTTPS or HTTP based on the current protocol. ```javascript var _gaq = _gaq || []; _gaq.push(['_setAccount', config.googleAnalytics]); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); ``` -------------------------------- ### Implement Google Analytics Tracking in JavaScript Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/docs/utils_Utils.js.html This JavaScript code initializes Google Analytics tracking for a web page using the traditional `_gaq` asynchronous tracking snippet. It sets the Google Analytics account ID from the `config` object and tracks a pageview. The script dynamically creates and inserts the Google Analytics JavaScript file into the document, ensuring non-blocking loading and compatibility with both HTTP and HTTPS protocols. ```JavaScript var _gaq = _gaq || []; _gaq.push(['_setAccount', config.googleAnalytics]); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); ``` -------------------------------- ### Utils Module API Reference Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/docs/utils_Utils.js.html Comprehensive API documentation for the `Utils` module, detailing its utility methods for type checking variables. This module provides static functions to determine the type of a given variable, such as checking if it's a function or undefined. ```APIDOC Utils: isFunction(variable: any): boolean - Determines whether a variable is a `Function`. - Parameters: - variable: The variable to determine the type of. - Returns: `true` if the variable is a function, `false` otherwise. isUndefined(variable: any): boolean - Determines whether a variable is `undefined`. - Parameters: - variable: The variable to determine the type of. - Returns: `true` if the variable is undefined, `false` otherwise. ``` -------------------------------- ### Interaction Class API: Members and Methods Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/docs/interaction_InteractionData.js.html This entry details the API for the `Interaction` class, which manages interaction events within a Three.js scene. It includes various members for configuration and state, such as camera, renderer, and cursor styles, along with methods for event handling (on, off, emit), hit testing, and cursor management. ```APIDOC Interaction: Members: autoPreventDefault: Boolean camera: THREE.Camera currentCursorMode: String cursorStyles: Object eventData: Object interactionFrequency: Number mouse: THREE.Vector2 moveWhenInside: Boolean renderer: THREE.WebGLRenderer scene: THREE.Scene supportsPointerEvents: Boolean supportsTouchEvents: Boolean Methods: destroy() - Cleans up the interaction instance. emit(eventName, eventData) - Emits a custom event. hitTest(object, eventData) - Performs a hit test on a given object. mapPositionToPoint(position) - Maps a 3D position to a 2D screen point. off(eventName, listener) - Removes an event listener. on(eventName, listener) - Adds an event listener. once(eventName, listener) - Adds an event listener that fires only once. setCursorMode(mode) - Sets the cursor mode. setTargetElement(element) - Sets the target DOM element for interaction events. ``` -------------------------------- ### APIDOC: Ticker Class Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/docs/index.html The `Ticker` class provides a simple event emitter for managing animation frames or timed events. It allows registering and unregistering listeners for 'tick' events, and controlling the start and stop of the ticker. ```APIDOC Ticker: Methods: emit(eventName: string, ...args: any[]): void - Dispatches a custom event with the given name and arguments. - Parameters: - eventName: The name of the event to emit. - ...args: Any additional arguments to pass to the listeners. off(eventName: string, listener: Function, context?: object): void - Removes an event listener for a specific event. - Parameters: - eventName: The name of the event. - listener: The function to remove. - context: (Optional) The context (this) the listener was bound to. on(eventName: string, listener: Function, context?: object): void - Registers an event listener for a specific event. - Parameters: - eventName: The name of the event to listen for. - listener: The function to call when the event occurs. - context: (Optional) The context (this) for the listener function. once(eventName: string, listener: Function, context?: object): void - Registers an event listener that will be called only once for a specific event. - Parameters: - eventName: The name of the event to listen for. - listener: The function to call when the event occurs. - context: (Optional) The context (this) for the listener function. start(): void - Starts the ticker, causing it to emit 'tick' events (e.g., on each animation frame). stop(): void - Stops the ticker, preventing further 'tick' events from being emitted. ``` -------------------------------- ### Importing and Initializing three.interaction.js Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/docs/interaction_Interaction.js.html This snippet demonstrates how to import the `Interaction` class and initialize it with a Three.js renderer, scene, and camera. It also shows how to bind various interaction events (touchstart, mousedown, pointerdown) to a mesh and how events bubble up the display tree. ```JavaScript import { Scene, PerspectiveCamera, WebGLRenderer, Mesh, BoxGeometry, MeshBasicMaterial } 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); const interaction = new Interaction(renderer, scene, camera); // then you can bind every interaction event with any mesh which you had `add` into `scene` before const cube = new Mesh( new BoxGeometry(1, 1, 1), new MeshBasicMaterial({ color: 0xffffff }), ); scene.add(cube); cube.on('touchstart', ev => { console.log(ev); }); cube.on('mousedown', ev => { console.log(ev); }); cube.on('pointerdown', ev => { console.log(ev); }); // and so on ... // you can also listen on parent-node or any display-tree node, // source event will bubble up along with display-tree. // you can stop the bubble-up by invoke ev.stopPropagation function. scene.on('touchstart', ev => { console.log(ev); }) ``` -------------------------------- ### Ticker Class API: Methods Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/docs/interaction_InteractionData.js.html This section details the methods of the `Ticker` class, which provides a simple event emitter for managing animation loops or timed events. It includes standard event handling methods (on, off, emit, once) and controls for starting and stopping the ticker. ```APIDOC Ticker: Methods: emit(eventName, ...args) - Emits a custom event with optional arguments. off(eventName, listener) - Removes an event listener. on(eventName, listener) - Adds an event listener. once(eventName, listener) - Adds an event listener that fires only once. start() - Starts the ticker. stop() - Stops the ticker. ``` -------------------------------- ### Initialize Three.js Scene, Renderer, Camera, and Interaction Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/examples/interaction-overlap/index.html This snippet sets up the fundamental components of a Three.js application, including the camera, WebGL renderer, and scene. It also initializes the `THREE.Interaction` library, linking it to the renderer, scene, and camera to enable interactive capabilities for 3D objects. ```JavaScript window.addEventListener('resize', onWindowResize, false); var WIDTH = window.innerWidth; var HEIGHT = window.innerHeight; var camera = new THREE.PerspectiveCamera(60, WIDTH / HEIGHT, 0.01, 100); var renderer = new THREE.WebGLRenderer({ canvas: document.querySelector('#webgl'), antialias: true, }); renderer.setClearColor(0x41b882); renderer.setSize(WIDTH, HEIGHT); var scene = new THREE.Scene(); var group = new THREE.Group(); var interaction = new THREE.Interaction(renderer, scene, camera); ``` -------------------------------- ### Initialize Three.js Scene and Handle Cube Interactions Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/examples/interaction/index.html This JavaScript code initializes a Three.js scene, sets up a camera and WebGL renderer, creates a 3D cube, and attaches a comprehensive set of interaction event listeners to the cube using the `THREE.Interaction` library. It demonstrates how to capture pointer, mouse, and touch events on a specific 3D object within the scene, logging events to the console and triggering a visual 'blink' effect. The scene includes ambient and point lights, and the cube continuously rotates. ```javascript window.addEventListener('resize', onWindowResize, false); var WIDTH = window.innerWidth; var HEIGHT = window.innerHeight; var camera = new THREE.PerspectiveCamera(60, WIDTH / HEIGHT, 0.01, 100); var renderer = new THREE.WebGLRenderer({ canvas: document.querySelector('#webgl'), antialias: true, }); renderer.setClearColor(0x41b882); renderer.setSize(WIDTH, HEIGHT); var scene = new THREE.Scene(); var interaction = new THREE.Interaction(renderer, scene, camera); var cube = new THREE.Mesh( new THREE.BoxGeometry(3, 3, 3), new THREE.MeshPhongMaterial({ color: 0xffffff }) ); cube.cursor = 'pointer'; cube.position.y = -2; cube.position.z = -10; cube.name = 'cube'; scene.add(cube); var ambient = new THREE.AmbientLight( 0x666666 ); scene.add( ambient ); var light = new THREE.PointLight(0xffffff); light.position.set(20, 50, 10); scene.add(light); var box = document.querySelector('#event-box'); cube.on('pointerdown', function(ev) { blink(document.querySelector('#pointerdown')); console.log('%c' + cube.name + '%c => pointerdown', 'color: #fff; background: #41b882; padding: 3px 4px;', 'color: #41b882; background: #fff;'); }); cube.on('pointermove', function(ev) { blink(document.querySelector('#pointermove')); console.log('%c' + cube.name + '%c => pointermove', 'color: #fff; background: #41b882; padding: 3px 4px;', 'color: #41b882; background: #fff;'); }); cube.on('pointerup', function(ev) { blink(document.querySelector('#pointerup')); console.log('%c' + cube.name + '%c => pointerup', 'color: #fff; background: #41b882; padding: 3px 4px;', 'color: #41b882; background: #fff;'); }); cube.on('pointerout', function(ev) { blink(document.querySelector('#pointerout')); console.log('%c' + cube.name + '%c => pointerout', 'color: #fff; background: #41b882; padding: 3px 4px;', 'color: #41b882; background: #fff;'); }); cube.on('click', function(ev) { blink(document.querySelector('#click')); console.log('%c' + cube.name + '%c => click', 'color: #fff; background: #41b882; padding: 3px 4px;', 'color: #41b882; background: #fff;'); }); cube.on('touchstart', function(ev) { blink(document.querySelector('#touchstart')); console.log('%c' + cube.name + '%c => touchstart', 'color: #fff; background: #41b882; padding: 3px 4px;', 'color: #41b882; background: #fff;'); }); cube.on('touchmove', function(ev) { blink(document.querySelector('#touchmove')); ev.data.originalEvent.preventDefault(); console.log('%c' + cube.name + '%c => touchmove', 'color: #fff; background: #41b882; padding: 3px 4px;', 'color: #41b882; background: #fff;'); }); cube.on('touchend', function(ev) { blink(document.querySelector('#touchend')); console.log('%c' + cube.name + '%c => touchend', 'color: #fff; background: #41b882; padding: 3px 4px;', 'color: #41b882; background: #fff;'); }); cube.on('mousemove', function(ev) { blink(document.querySelector('#mousemove')); console.log('%c' + cube.name + '%c => mousemove', 'color: #fff; background: #41b882; padding: 3px 4px;', 'color: #41b882; background: #fff;'); }); cube.on('mousedown', function(ev) { blink(document.querySelector('#mousedown')); console.log('%c' + cube.name + '%c => mousedown', 'color: #fff; background: #41b882; padding: 3px 4px;', 'color: #41b882; background: #fff;'); }); cube.on('mouseout', function(ev) { blink(document.querySelector('#mouseout')); console.log('%c' + cube.name + '%c => mouseout', 'color: #fff; background: #41b882; padding: 3px 4px;', 'color: #41b882; background: #fff;'); }); cube.on('mouseover', function(ev) { blink(document.querySelector('#mouseover')); console.log('%c' + cube.name + '%c => mouseover', 'color: #fff; background: #41b882; padding: 3px 4px;', 'color: #41b882; background: #fff;'); }); cube.on('mouseup', function(ev) { blink(document.querySelector('#mouseup')); console.log('%c' + cube.name + '%c => mouseup', 'color: #fff; background: #41b882; padding: 3px 4px;', 'color: #41b882; background: #fff;'); }); function render() { cube.rotation.y += 0.01; renderer.render(scene, camera); requestAnimationFrame(render); } render(); function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); } function blink(dom) { clearTimeout(dom.timer); dom.className = 'marker active'; dom.timer = setTimeout(function(){ dom.className = 'marker'; }, 300); } ``` -------------------------------- ### Configure and Initialize THREE.DRACOLoader Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/examples/libs/three/examples/js/libs/draco/README.md This JavaScript snippet demonstrates how to configure the decoder path for `THREE.DRACOLoader` and optionally override WASM support detection. It then initializes a new instance of `THREE.DRACOLoader` for loading Draco compressed 3D models. ```js THREE.DRACOLoader.setDecoderPath('path/to/decoders/'); THREE.DRACOLoader.setDecoderConfig({type: 'js'}); // (Optional) Override detection of WASM support. var dracoLoader = new THREE.DRACOLoader(); ``` -------------------------------- ### Ticker Class API Reference Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/docs/patch_Object3D.js.html Provides a mechanism for managing and dispatching update events, useful for animations or continuous processes. ```APIDOC Ticker: Methods: emit(eventName: String, data: Object): Emits a custom event with associated data. off(eventName: String, handler: Function): Removes an event listener for a specified event. on(eventName: String, handler: Function): Adds an event listener for a specified event. once(eventName: String, handler: Function): Adds an event listener that will be invoked only once. start(): Starts the ticker, beginning the dispatch of update events. stop(): Stops the ticker, pausing the dispatch of update events. ``` -------------------------------- ### InteractionEvent Class API Reference Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/docs/patch_Object3D.js.html Represents an interaction event dispatched by the system, containing information about the target, data, and intersection results. ```APIDOC InteractionEvent: Members: currentTarget: THREE.Object3D - The current object whose event listener is being processed. data: InteractionData - The interaction data associated with this event. intersects: Array - An array of intersection results from the raycast. stopped: Boolean - Indicates if event propagation has been stopped. target: THREE.Object3D - The initial interactive Three.js object that triggered the event. type: String - The type of the interaction event (e.g., 'click', 'mouseover'). Methods: stopPropagation(): Prevents the event from propagating further up the object hierarchy. ``` -------------------------------- ### InteractionData Class API Reference Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/docs/patch_Object3D.js.html Defines the structure of data associated with an interaction event, providing details about the pointer, button states, and event coordinates. ```APIDOC InteractionData: Members: button: Number - The button number that was pressed (e.g., 0 for left, 1 for middle, 2 for right). buttons: Number - A bitmask indicating which buttons are currently pressed. global: THREE.Vector2 - The global coordinates of the pointer on the screen. height: Number - The height of the contact geometry (for touch/pointer events). identifier: Number - A unique ID for the pointer (for multi-touch/pointer). isPrimary: Boolean - True if this is the primary pointer for a multi-pointer interaction. originalEvent: Event - The original DOM event object that triggered the interaction. pointerId: Number - The ID of the pointer (for Pointer Events). pointerType: String - The type of pointer (e.g., 'mouse', 'pen', 'touch'). pressure: Number - The pressure of the pointer input (0 to 1). rotationAngle: Number - The rotation angle of the contact geometry (for touch/pointer events). tangentialPressure: Number - The tangential pressure of the pointer input. target: THREE.Object3D - The interactive Three.js object that is the target of the event. tiltX: Number - The X-axis tilt of the pointer. tiltY: Number - The Y-axis tilt of the pointer. twist: Number - The twist of the pointer. width: Number - The width of the contact geometry (for touch/pointer events). ``` -------------------------------- ### Extend EventDispatcher with 'once' method Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/docs/patch_EventDispatcher.js.html Binds an event listener that will only be triggered once. After the event is emitted, the listener is automatically removed. It ensures the provided callback is a function. ```JavaScript EventDispatcher.prototype.once = function(type, fn) { if (!Utils.isFunction(fn)) return; const cb = (ev) => { fn(ev); this.off(type, cb); }; this.on(type, cb); return this; }; ``` -------------------------------- ### Initialize and use three.interaction with Three.js objects Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/README.md Demonstrates how to import and initialize `three.interaction` with a Three.js scene, camera, and renderer. It shows how to attach various interaction events (click, touch, mouse) to a Mesh object and listen for events on parent nodes like the Scene, illustrating event bubbling. ```javascript import { Scene, PerspectiveCamera, WebGLRenderer, Mesh, BoxGeometry, MeshBasicMaterial } 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); // new a interaction, then you can add interaction-event with your free style const interaction = new Interaction(renderer, scene, camera); const cube = new Mesh( new BoxGeometry(1, 1, 1), new MeshBasicMaterial({ color: 0xffffff }) ); scene.add(cube); cube.cursor = 'pointer'; cube.on('click', function(ev) {}); cube.on('touchstart', function(ev) {}); cube.on('touchcancel', function(ev) {}); cube.on('touchmove', function(ev) {}); cube.on('touchend', function(ev) {}); cube.on('mousedown', function(ev) {}); cube.on('mouseout', function(ev) {}); cube.on('mouseover', function(ev) {}); cube.on('mousemove', function(ev) {}); cube.on('mouseup', function(ev) {}); // and so on ... /** * you can also listen on parent-node or any display-tree node, * source event will bubble up along with display-tree. * you can stop the bubble-up by invoke ev.stopPropagation function. */ scene.on('touchstart', ev => { console.log(ev); }) scene.on('touchmove', ev => { console.log(ev); }) ``` -------------------------------- ### Extend EventDispatcher with 'off' method Source: https://github.com/jasonchen1982/three.interaction.js/blob/master/docs/patch_EventDispatcher.js.html Proxies the `removeEventListener` function, allowing for event unbinding. It removes a previously bound callback for a specific event type. ```JavaScript EventDispatcher.prototype.off = function(type, fn) { this.removeEventListener(type, fn); return this; }; ```