### Combined Development Setup Commands Source: https://github.com/tweenjs/tween.js/blob/main/docs/contributor_guide.md A concise sequence of commands to clone the repository, navigate into the project directory, and install development dependencies. ```bash git clone https://github.com/tweenjs/tween.js.git cd tween.js npm install ``` -------------------------------- ### Start a Tween with Time and Options Source: https://github.com/tweenjs/tween.js/blob/main/docs/user_guide.md The `start` method can accept a `time` argument to delay the start, and a boolean to restart from current values. If no time is specified, the tween starts on the next update. ```javascript tween.start(time, restartFromCurrentValues) ``` -------------------------------- ### Install and Run Tests Source: https://github.com/tweenjs/tween.js/blob/main/README.md Commands to set up the development environment and execute the test suite. ```bash npm install ``` ```bash npm test ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/tweenjs/tween.js/blob/main/docs/contributor_guide.md Install the necessary development dependencies for tween.js using npm. ```bash npm install ``` -------------------------------- ### npm install tween.js Source: https://github.com/tweenjs/tween.js/wiki/Old-change-log Instructions for installing tween.js as an official npm module. This was noted in release r11. ```bash ```npm install tween.js``` ``` -------------------------------- ### Install tween.js with npm and bower Source: https://github.com/tweenjs/tween.js/wiki/Old-change-log Provides instructions on how to install tween.js using package managers like npm and bower. This information was highlighted in release r14. ```bash Make it explicit that you can install tween.js with `npm` and `bower` ``` -------------------------------- ### Added tween.onStart() Source: https://github.com/tweenjs/tween.js/wiki/Old-change-log Introduces the `tween.onStart()` method for handling the start event of a tween. This was added in release r7. ```javascript Added tween.onStart(). ``` -------------------------------- ### Setup and Animation Loop Source: https://github.com/tweenjs/tween.js/blob/main/examples/11_stop_all_chained_tweens.html Initializes the animation group and sets up the requestAnimationFrame loop for updating tweens. Ensure the Tween.js library is imported. ```javascript import * as TWEEN from '../dist/tween.esm.js' const group = new TWEEN.Group() function animate(time) { group.update(time) requestAnimationFrame(animate) } animate() ``` -------------------------------- ### Start a tween animation Source: https://github.com/tweenjs/tween.js/blob/main/docs/user_guide.md After creating and configuring a tween, you must call the `start()` method to make it active and begin the animation. ```javascript // And set it to start tween.start() ``` -------------------------------- ### start() and stop() - Control Animation Playback Source: https://context7.com/tweenjs/tween.js/llms.txt Methods to manage the lifecycle of the animation. ```APIDOC ## start() and stop() ### Description start() activates the tween to begin animating. stop() halts the tween and any chained tweens immediately. ### Parameters - **startTime** (Number) - Optional - Specific time to begin the animation. - **startFromCurrentValues** (Boolean) - Optional - Whether to start from current object values. ``` -------------------------------- ### Install Tween.js via npm Source: https://github.com/tweenjs/tween.js/blob/main/README.md Add the library as a dependency to your project using the npm package manager. ```bash npm install @tweenjs/tween.js ``` -------------------------------- ### Add Delays to Tweens with delay() and repeatDelay() Source: https://context7.com/tweenjs/tween.js/llms.txt Use delay() to set a wait period before a tween starts and repeatDelay() to set the delay between repetitions. This example demonstrates a tween that waits 500ms before starting, repeats 3 times, with a 200ms delay between each repetition. ```javascript import { Tween, Easing } from '@tweenjs/tween.js' const box = { rotation: 0 } const tween = new Tween(box) .to({ rotation: 360 }, 1000) .delay(500) // Wait 500ms before first animation .repeat(3) // Repeat 3 times after initial run .repeatDelay(200) // Wait 200ms between each repetition .easing(Easing.Sinusoidal.InOut) .onUpdate(() => { element.style.transform = `rotate(${box.rotation}deg)` }) .start() // Timeline: // 0ms - start() called // 500ms - animation begins (delay) // 1500ms - first run complete // 1700ms - second run begins (repeatDelay) // 2700ms - second run complete // ... ``` -------------------------------- ### Sequence Tweens with chain() Source: https://context7.com/tweenjs/tween.js/llms.txt Use chain() to link tweens sequentially, so one starts automatically after the previous one finishes. This example creates a circular chain, making the animation loop infinitely by chaining three tweens: move right, move down, and move back to the start. ```javascript import { Tween, Easing, Group } from '@tweenjs/tween.js' const position = { x: 100, y: 100, rotation: 0 } const element = document.getElementById('target') const group = new Group() // Move right const moveRight = new Tween(position) .to({ x: 400 }, 1000) .easing(Easing.Quadratic.Out) .onUpdate(updateElement) // Move down const moveDown = new Tween(position) .to({ y: 300 }, 1000) .easing(Easing.Quadratic.Out) .onUpdate(updateElement) // Move back to start const moveBack = new Tween(position) .to({ x: 100, y: 100 }, 1500) .easing(Easing.Elastic.Out) .onUpdate(updateElement) // Chain sequence: right -> down -> back -> right (infinite loop) moveRight.chain(moveDown) moveDown.chain(moveBack) moveBack.chain(moveRight) // Start the first tween moveRight.start() group.add(moveRight, moveDown, moveBack) function updateElement() { element.style.transform = `translate(${position.x}px, ${position.y}px)` } function animate(time) { group.update(time) requestAnimationFrame(animate) } requestAnimationFrame(animate) ``` -------------------------------- ### Chain Multiple Tweens to Start Simultaneously Source: https://github.com/tweenjs/tween.js/blob/main/docs/user_guide.md Chain multiple tweens to another tween so they all start animating at the same time once the initial tween finishes. ```javascript tweenA.chain(tweenB, tweenC) ``` -------------------------------- ### Initialize and start a tween from current values Source: https://github.com/tweenjs/tween.js/blob/main/examples/18_start_from_current_values.html Uses startFromCurrentValues to allow dynamic updates to the target object via arrow buttons before the animation begins. ```javascript import * as TWEEN from '../dist/tween.esm.js' const position = {x: 400, y: 200} const target = document.getElementById('target') const tween = new TWEEN.Tween(position) .to({x: 700, y: 200}, 2000) .easing(TWEEN.Easing.Elastic.InOut) .onUpdate(update) document.getElementById('start-tween').addEventListener('click', () => { tween.startFromCurrentValues() // start the tween from its current position animate() // call animate as we unregister the handler if TWEEN.update(time) returns false }) registerArrowButtonEventListeners() animate() function animate(time) { if (tween.update(time)) requestAnimationFrame(animate) } function update() { target.style.transform = `translate(${position.x}px, ${position.y}px)` } //Add event listeners to each of the arrow buttons function registerArrowButtonEventListeners() { document.getElementById('up').addEventListener('click', moveUp) document.getElementById('down').addEventListener('click', moveDown) document.getElementById('left').addEventListener('click', moveLeft) document.getElementById('right').addEventListener('click', moveRight) } // Arrow button callbacks function moveLeft() { position.x -= 20 update() } function moveRight() { position.x += 20 update() } function moveUp() { position.y -= 20 update() } function moveDown() { position.y += 20 update() } ``` -------------------------------- ### Start Tween from Current Values Source: https://github.com/tweenjs/tween.js/blob/main/docs/user_guide.md Use `startFromCurrentValues` as an alias for `tween.start(undefined, true)` to make a previously used tween start from the target object's last values. ```javascript tween.startFromCurrentValues() ``` -------------------------------- ### Control Animation Playback Source: https://context7.com/tweenjs/tween.js/llms.txt Manage tween execution with start, delayed start, manual value resets, and immediate stopping. ```javascript import { Tween } from '@tweenjs/tween.js' const position = { x: 0, y: 0 } const tween = new Tween(position).to({ x: 500, y: 300 }, 2000) // Start immediately tween.start() // Start at specific time tween.start(performance.now() + 1000) // Delayed start by 1 second // Start from current values (useful for re-running) tween.stop() position.x = 250 // Manually changed tween.startFromCurrentValues() // Continues from x=250 instead of 0 // Stop animation and all chained tweens document.getElementById('stopBtn').onclick = () => { tween.stop() console.log('Animation stopped at x:', position.x) } // Animation loop function animate(time) { if (tween.update(time)) { requestAnimationFrame(animate) } } requestAnimationFrame(animate) ``` -------------------------------- ### Chain tween configuration methods Source: https://github.com/tweenjs/tween.js/blob/main/docs/user_guide.md Tween.js allows chaining method calls like `to()` and `start()` for more concise code. Each method returns the tween instance, enabling this pattern. ```javascript const tween = new Tween(position).to({x: 200}, 1000).start() ``` -------------------------------- ### Delay Tween Start Source: https://github.com/tweenjs/tween.js/blob/main/docs/user_guide.md Use the `delay` method to set a delay in milliseconds before a tween begins execution after `start()` is called. ```javascript tween.delay(1000) tween.start() ``` -------------------------------- ### Setup and Animation Loop for Dynamic Tweening Source: https://github.com/tweenjs/tween.js/blob/main/examples/07_dynamic_to.html Initializes the animation scene, canvas, and tween objects. The `animate` function updates the tweens and redraws the scene on each frame. Requires `drawRabbit` and `drawFox` functions to be defined elsewhere. ```javascript import {Tween, Group, Easing} from '../dist/tween.esm.js' import {drawRabbit, drawFox} from './js/drawings.js' startScene('scene1', false) startScene('scene2', true) function startScene(id, dynamic) { const group = new Group() const width = 480 const height = 320 const scene = document.getElementById(id) const canvas = document.createElement('canvas') canvas.width = width canvas.height = height scene.appendChild(canvas) const context = canvas.getContext('2d') const rabbit = {x: width - 50, y: 50} new Tween(rabbit, group) .to({x: width - 50, y: height - 50}, 3000) .easing(Easing.Exponential.InOut) .start() const fox = {x: 50, y: 50} new Tween(fox, group).to(rabbit, 3000).dynamic(dynamic).duration(3000).easing(Easing.Exponential.InOut).start() animate() function animate(time) { group.update(time) // draw background context.fillStyle = 'rgb(240,250,240)' context.fillRect(0, 0, width, height) drawRabbit(context, rabbit.x, rabbit.y, 'rgb(150,150,150)') drawFox(context, fox.x, fox.y, 'rgb(200,80,80)') requestAnimationFrame(animate) } } ``` -------------------------------- ### Array Interpolation Setup with Tween.js Source: https://github.com/tweenjs/tween.js/blob/main/examples/06_array_interpolation.html Sets up the animation group, target element, and appends different interpolation paths. Ensure the target element exists and necessary imports are available. ```javascript import {createPath, xA, x0, yA, y0} from './js/createPath.js' import * as TWEEN from '../dist/tween.esm.js' const group = new TWEEN.Group() const target = document.getElementById('target') if (!target) throw 'missing element' target.appendChild(createPath(group, 'Linear', TWEEN.Interpolation.Linear)) target.appendChild(createPath(group, 'Bezier', TWEEN.Interpolation.Bezier)) target.appendChild(createPath(group, 'CatmullRom', TWEEN.Interpolation.CatmullRom)) target.appendChild(document.createElement('br')) xA.push(x0) yA.push(y0) target.appendChild(createPath(group, 'start === end', TWEEN.Interpolation.Linear)) target.appendChild(createPath(group, '', TWEEN.Interpolation.Bezier)) target.appendChild(createPath(group, '', TWEEN.Interpolation.CatmullRom)) animate() function animate(time) { requestAnimationFrame(animate) group.update(time) } ``` -------------------------------- ### Tween Lifecycle Methods Source: https://github.com/tweenjs/tween.js/blob/main/docs/user_guide.md Methods to control the execution state of a tween, including starting, stopping, pausing, and updating. ```APIDOC ## Tween Lifecycle Methods ### Description Methods to manage the lifecycle of a tween instance. ### Methods - **start(time, jumpToStart)**: Starts the tween. `time` (optional) sets a specific start time. `jumpToStart` (boolean) if true, starts from current target values. - **stop()**: Cancels the tween. - **pause()**: Pauses the tween execution. - **update(time)**: Updates the tween state based on the provided time. ### Request Example ```javascript tween.start(); tween.pause(); tween.update(performance.now()); tween.stop(); ``` ``` -------------------------------- ### Integrate tween.js with Three.js Source: https://context7.com/tweenjs/tween.js/llms.txt This example demonstrates animating Three.js objects, including camera movement and cube properties like position, rotation, and scale. ```javascript import * as THREE from 'three' import { Tween, Easing, Group } from '@tweenjs/tween.js' // Setup Three.js scene const scene = new THREE.Scene() const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000) const renderer = new THREE.WebGLRenderer() renderer.setSize(window.innerWidth, window.innerHeight) document.body.appendChild(renderer.domElement) // Create a cube const geometry = new THREE.BoxGeometry() const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 }) const cube = new THREE.Mesh(geometry, material) scene.add(cube) camera.position.z = 5 const group = new Group() // Animate cube position directly (Three.js objects work with tween.js) const moveTween = new Tween(cube.position) .to({ x: 2, y: 1, z: -2 }, 2000) .easing(Easing.Elastic.Out) .start() // Animate cube rotation const rotateTween = new Tween(cube.rotation) .to({ x: Math.PI * 2, y: Math.PI }, 3000) .easing(Easing.Quadratic.InOut) .repeat(Infinity) .start() // Animate cube scale const scaleTween = new Tween(cube.scale) .to({ x: 1.5, y: 1.5, z: 1.5 }, 1000) .easing(Easing.Back.Out) .yoyo(true) .repeat(Infinity) .start() // Animate camera const cameraTween = new Tween(camera.position) .to({ x: 3, y: 2, z: 8 }, 4000) .easing(Easing.Sinusoidal.InOut) .onUpdate(() => { camera.lookAt(cube.position) }) .start() group.add(moveTween, rotateTween, scaleTween, cameraTween) function animate(time) { requestAnimationFrame(animate) group.update(time) renderer.render(scene, camera) } animate() ``` -------------------------------- ### Synchronize tweens with player time Source: https://github.com/tweenjs/tween.js/blob/main/docs/user_guide.md This example shows how to use an explicit time value, such as the current time of a player, when calling `tween.update()` to ensure animations are synchronized. ```javascript let currentTime = player.currentTime tween.update(currentTime) ``` -------------------------------- ### Define Custom Easing Function Source: https://github.com/tweenjs/tween.js/blob/main/docs/user_guide.md Example of a step-ladder easing function that returns integer increments. ```javascript function tenStepEasing(k) { return Math.floor(k * 10) / 10 } ``` -------------------------------- ### Utilize Tween.js Lifecycle Callbacks Source: https://context7.com/tweenjs/tween.js/llms.txt Implement lifecycle callbacks like onStart, onEveryStart, onUpdate, onRepeat, onComplete, and onStop to execute custom logic at specific points during the tween's animation. This example logs messages to the console for each event and updates a progress bar. ```javascript import { Tween, Easing } from '@tweenjs/tween.js' const data = { progress: 0 } const tween = new Tween(data) .to({ progress: 100 }, 3000) .repeat(2) .easing(Easing.Linear.None) .onStart((obj) => { console.log('Animation started!') // Called once }) .onEveryStart((obj) => { console.log('Starting iteration') // Called on start and each repeat }) .onUpdate((obj, elapsed) => { // elapsed is 0-1 representing progress within current iteration progressBar.style.width = `${obj.progress}% progressText.textContent = `${Math.round(obj.progress)}%` }) .onRepeat((obj) => { console.log('Completed one iteration, repeating...') }) .onComplete((obj) => { console.log('All iterations complete!') showCompletionMessage() }) .onStop((obj) => { console.log('Animation was stopped at:', obj.progress) }) .start() ``` -------------------------------- ### Tween to Relative Values with Repeat Source: https://github.com/tweenjs/tween.js/blob/main/examples/09_relative_values.html Demonstrates tweening to relative values using the `to` method with a relative offset. This example also shows how to use `repeat` to loop the animation. ```javascript import TWEEN from "../dist/tween.esm.js"; const target1 = { prop: 0 }; const tween1 = new TWEEN.Tween(target1) .to({ prop: 100 }, 1000) .repeat(Infinity) .start(); const target2 = { prop: 0 }; const tween2 = new TWEEN.Tween(target2) .to({ prop: -100 }, 1000) .repeat(Infinity) .start(); function animate(time) { requestAnimationFrame(animate); TWEEN.update(time); } animate(performance.now()); ``` -------------------------------- ### Animate three.js object properties Source: https://github.com/tweenjs/tween.js/blob/main/docs/user_guide.md This example demonstrates animating the position properties (x, y, z) of a three.js object within a typical animation loop that includes rendering. ```javascript const tween = new Tween(cube.position).to({x: 100, y: 100, z: 100}, 10000).start() animate() function animate() { requestAnimationFrame(animate) tween.update() threeRenderer.render(scene, camera) } ``` -------------------------------- ### Apply Relative and Absolute Tween Values Source: https://github.com/tweenjs/tween.js/blob/main/docs/user_guide.md Shows how to use string-quoted relative values to calculate targets based on the object's state at the time of start. ```javascript // This will make the `x` property be 100, always const absoluteTween = new Tween(absoluteObj).to({x: 100}) // Suppose absoluteObj.x is 0 now absoluteTween.start() // Makes x go to 100 // Suppose absoluteObj.x is -100 now absoluteTween.start() // Makes x go to 100 // In contrast... // This will make the `x` property be 100 units more, // relative to the actual value when it starts const relativeTween = new Tween(relativeObj).to({x: '+100'}) // Suppose relativeObj.x is 0 now relativeTween.start() // Makes x go to 0 +100 = 100 // Suppose relativeObj.x is -100 now relativeTween.start() // Makes x go to -100 +100 = 0 ``` -------------------------------- ### Chain Two Tweens Source: https://github.com/tweenjs/tween.js/blob/main/docs/user_guide.md Use the `chain` method to make one tween start after another finishes. Calling `tweenA.chain(tweenB)` modifies tweenA. ```javascript tweenA.chain(tweenB) ``` -------------------------------- ### Animate DOM Elements with CSS Transforms Source: https://context7.com/tweenjs/tween.js/llms.txt This example animates DOM elements using CSS transforms for better performance. It chains entrance, pulse, and exit animations. ```javascript import { Tween, Easing, Group } from '@tweenjs/tween.js' const group = new Group() const element = document.getElementById('box') const state = { x: 100, y: 100, rotation: 0, scale: 1, opacity: 1 } // Entrance animation const entrance = new Tween(state) .to({ x: 400, y: 200, rotation: 360, scale: 1.5 }, 2000) .easing(Easing.Elastic.Out) .delay(500) .onUpdate(render) // Hover/pulse effect const pulse = new Tween(state) .to({ scale: 1.2 }, 300) .easing(Easing.Quadratic.Out) .yoyo(true) .repeat(3) .onUpdate(render) // Exit animation const exit = new Tween(state) .to({ y: 600, opacity: 0, rotation: 720 }, 1000) .easing(Easing.Back.In) .onUpdate(render) .onComplete(() => { element.style.display = 'none' }) // Chain: entrance -> pulse -> exit entrance.chain(pulse) pulse.chain(exit) // Start the sequence entrance.start() group.add(entrance, pulse, exit) function render() { // Use transform for GPU acceleration element.style.transform = ` translate3d(${state.x}px, ${state.y}px, 0) rotate(${state.rotation}deg) scale(${state.scale}) ` element.style.opacity = state.opacity } function animate(time) { group.update(time) if (!group.allStopped()) { requestAnimationFrame(animate) } } requestAnimationFrame(animate) ``` -------------------------------- ### Synchronize Tween with Video Playback Source: https://github.com/tweenjs/tween.js/blob/main/examples/05_video_and_time.html Initialize and animate a tween synchronized with video playback. The tween starts at the video's current time and updates its progress based on the video's current time during playback. Ensure the video is ready before updating the tween. ```javascript import * as TWEEN from '../dist/tween.esm.js' let video let tween = null playButton.addEventListener('click', function () { init() animate() }) function init() { const output = document.createElement('div') const target = document.getElementById('target') target.appendChild(output) video = document.getElementById('video') video.addEventListener( 'play', function () { tween = new TWEEN.Tween({x: 50, y: 0}) .to({x: 400}, this.duration) .easing(TWEEN.Easing.Linear.None) .onUpdate(function (object) { const roundX = Math.round(object.x) const transform = 'translateX(' + roundX + 'px)' output.innerHTML = 'x == ' + roundX target.style.transform = transform }) .start(video.currentTime) }, false, ) video.play() } function animate() { if (tween && video.readyState === video.HAVE_ENOUGH_DATA) { tween.update(video.currentTime) } requestAnimationFrame(animate) } ``` -------------------------------- ### Dynamic Interpolation with Moving Targets Source: https://github.com/tweenjs/tween.js/blob/main/examples/07a_dynamic_to_two_array_values.html Use `.dynamic(true)` to enable dynamic interpolation where the target values can change during the tween. This example animates a fox towards two rabbits that are also moving. ```javascript import * as TWEEN from '../dist/tween.esm.js' import {drawRabbit, drawFox} from './js/drawings.js' startScene('scene1', false) startScene('scene2', true) function startScene(id, dynamic) { const group = new TWEEN.Group() const width = 480 const height = 320 const scene = document.getElementById(id) const canvas = document.createElement('canvas') canvas.width = width canvas.height = height scene.appendChild(canvas) const context = canvas.getContext('2d') const rabbit1 = { x: width * 0.8, y: 50, } new TWEEN.Tween(rabbit1, group) .to({x: width / 2, y: height - 50}, 2000) .easing(TWEEN.Easing.Cubic.InOut) .onUpdate(function ({x, y}) { rabbits.x[1] = x rabbits.y[1] = y }) .start() const rabbit2 = { x: width - 50, y: height - 50, } new TWEEN.Tween(rabbit2, group) .to({x: width / 3, y: 50}, 3000) .easing(TWEEN.Easing.Cubic.InOut) .onUpdate(function ({x, y}) { rabbits.x[2] = x rabbits.y[2] = y }) .start() const rabbits = { x: [rabbit1.x, rabbit2.x], y: [rabbit1.y, rabbit2.y], } const fox = { x: 50, y: 50, } new TWEEN.Tween(fox, group) .to(rabbits, 3000) .dynamic(dynamic) .interpolation(TWEEN.Interpolation.CatmullRom) .start() animate() function animate(time) { group.update(time) context.fillStyle = 'rgb(240,250,240)' context.fillRect(0, 0, width, height) drawRabbit(context, rabbit1.x, rabbit1.y, 'rgb(0,0,150)') drawRabbit(context, rabbit2.x, rabbit2.y, 'rgb(0,80,80)') drawFox(context, fox.x, fox.y, 'rgb(200,80,80)') requestAnimationFrame(animate) } } ``` -------------------------------- ### Loop Animations with repeat() and yoyo() Source: https://context7.com/tweenjs/tween.js/llms.txt Control animation looping using repeat() for a specific number of repetitions (or Infinity for endless loops) and yoyo() to reverse the animation direction on each repeat, creating a bouncing effect. This example shows both a fixed repeat count and an infinite yoyo loop. ```javascript import { Tween, Easing, Group } from '@tweenjs/tween.js' const group = new Group() const ball = { y: 0 } // Repeat 5 times (6 total runs) const tween1 = new Tween(ball) .to({ y: 200 }, 500) .repeat(5) .start() // Infinite loop with yoyo (bouncing effect) const tween2 = new Tween(ball) .to({ y: 200 }, 500) .repeat(Infinity) .yoyo(true) // Animates 0->200->0->200->0... .easing(Easing.Quadratic.InOut) .onUpdate(() => { element.style.transform = `translateY(${ball.y}px)` }) .start() group.add(tween2) function animate(time) { group.update(time) requestAnimationFrame(animate) } requestAnimationFrame(animate) ``` -------------------------------- ### Use onStart Callback Source: https://github.com/tweenjs/tween.js/blob/main/docs/user_guide.md Triggers an action, such as playing a sound, when a tween begins. ```javascript const tween = new Tween(obj).to({x: 100}).onStart(function () { sound.play() }) ``` -------------------------------- ### Demonstrate Tween Lifecycle Events Source: https://github.com/tweenjs/tween.js/blob/main/docs/user_guide.md Illustrates the execution order of onStart, onEveryStart, and onRepeat callbacks during a repeating tween. ```javascript const obj = {x: 0} const t = new Tween(obj) .to({x: 5}, 5) .repeat(Infinity) .onStart(() => { console.log('onStart') }) .onRepeat(() => { console.log('onRepeat') }) .onEveryStart(() => { console.log('onEveryStart') }) .start(0) for (let ticks = 0; ticks < 22; ticks += 1) { console.log('Tick', ticks) t.update(ticks) console.log(obj) console.log() } ``` -------------------------------- ### Navigate to Project Directory Source: https://github.com/tweenjs/tween.js/blob/main/docs/contributor_guide.md Change your current directory to the cloned tween.js project folder. ```bash cd tween.js ``` -------------------------------- ### Build Tween.js Manually Source: https://github.com/tweenjs/tween.js/blob/main/README.md Commands to clone the repository and build the library from source using npm. ```bash git clone https://github.com/tweenjs/tween.js cd tween.js npm install npm run build ``` -------------------------------- ### Run All Tests Source: https://github.com/tweenjs/tween.js/blob/main/docs/contributor_guide.md Execute the full test suite for tween.js, including unit and lint tests. ```bash npm test ``` -------------------------------- ### Tween Callbacks Source: https://github.com/tweenjs/tween.js/blob/main/docs/user_guide.md Explains the different callbacks available in Tween.js (onStart, onEveryStart, onStop, onUpdate, onComplete) and how to use them to execute custom logic at specific points in a tween's lifecycle. ```APIDOC ## Tween Callbacks ### Description Callbacks allow you to execute custom functions at specific moments during a tween's life cycle. All callbacks receive the tweened object as their sole parameter. ### `onUpdate` Callback #### Description Executed each time the tween is updated, after the values have been actually updated. Useful for manually updating properties or calling setters. #### Example ```javascript tween.onUpdate(function (object) { object.setA(object.propertyA); object.setB(object.propertyB); }); ``` ### `onStart` Callback #### Description Executed right before the tween starts animating, after any specified delay. This callback is executed only once per tween and is not run when the tween is repeated. #### Example ```javascript tween.onStart(function () { sound.play(); }); ``` ### `onEveryStart` Callback #### Description Similar to `onStart`, but this callback is executed on every repeat of the tween. ### `onStop` Callback #### Description Executed when a tween is explicitly stopped using `stop()`. It is not executed when a tween completes normally. This callback runs before any potential chained tween is stopped. ### `onComplete` Callback #### Description Executed when a tween finishes normally (i.e., it is not stopped prematurely). ### Callback Parameter - **object** (object) - The tweened object. ``` -------------------------------- ### Configure Import Map with CDN Source: https://github.com/tweenjs/tween.js/blob/main/README.md Map the package name to a specific CDN URL for easier imports across your scripts. ```html ``` -------------------------------- ### Staggering Tween animations with delay Source: https://github.com/tweenjs/tween.js/blob/main/examples/13_relative_start_time.html Uses the delay method to initiate animations at different times relative to the start call. ```javascript import * as TWEEN from '../dist/tween.esm.js' const position1 = {x: 100, y: 100, rotation: 0} const position2 = {x: 100, y: 300, rotation: 0} const target1 = document.getElementById('target1') const target2 = document.getElementById('target2') const tween1 = new TWEEN.Tween(position1) .to({x: 700, y: 200, rotation: 359}, 2000) .easing(TWEEN.Easing.Elastic.InOut) .onUpdate(update1) const tween2 = new TWEEN.Tween(position2).to({x: 500, y: 300, rotation: -90}, 2000).onUpdate(update2) tween1.delay(2000).start() tween2.delay(100).start() animate() function animate(time) { requestAnimationFrame(animate) tween1.update(time) tween2.update(time) } function update1() { target1.style.transform = `translate(${position1.x}px, ${position1.y}px) rotate(${Math.floor( position1.rotation, )}deg)` } function update2() { target2.style.transform = `translate(${position2.x}px, ${position2.y}px) rotate(${Math.floor( position2.rotation, )}deg)` } ``` -------------------------------- ### Set Repeat Delay Source: https://github.com/tweenjs/tween.js/blob/main/docs/user_guide.md The `repeatDelay` method sets the time in milliseconds between repetitions of a tween. If only `delay` is set, it applies to the initial start. ```javascript tween.delay(1000) tween.repeatDelay(500) tween.start() ``` -------------------------------- ### Import Tween.js from CDN Source: https://github.com/tweenjs/tween.js/blob/main/README.md Directly import the library from a CDN URL without requiring an import map. ```html ``` -------------------------------- ### Enable Yoyo Effect Source: https://github.com/tweenjs/tween.js/blob/main/docs/user_guide.md When used with `repeat`, `yoyo(true)` makes the tween bounce between start and end values. `yoyo(false)` is the default behavior. ```javascript tween.yoyo(false) // default value, animation will only go from start to end value tween.yoyo(true) // tween will 'yoyo' between start and end values ``` -------------------------------- ### 克隆并安装 tween.js 开发环境 Source: https://github.com/tweenjs/tween.js/blob/main/docs/contributor_guide_zh-CN.md 初始化开发环境的步骤,包括克隆仓库、进入目录以及安装依赖项。 ```bash git clone https://github.com/tweenjs/tween.js.git ``` ```bash cd tween.js ``` ```bash npm install ``` ```bash git clone https://github.com/tweenjs/tween.js.git cd tween.js npm install ``` -------------------------------- ### Clone tween.js Repository Source: https://github.com/tweenjs/tween.js/blob/main/docs/contributor_guide.md Clone the tween.js repository to your local machine to begin development. ```bash git clone https://github.com/tweenjs/tween.js.git ``` -------------------------------- ### Update Tween Values Source: https://github.com/tweenjs/tween.js/blob/main/docs/user_guide.md Call the `update` method within an animation loop to apply updated values to the target object. Ensure the tween has been started. ```javascript const tween = new Tween(someObject).to(/*...*/).start() function animate(time) { tween.update(time) requestAnimationFrame(animate) } ``` -------------------------------- ### Configure Import Map for Local node_modules Source: https://github.com/tweenjs/tween.js/blob/main/README.md Define an import map in your HTML to resolve the package name to a local file path. ```html ``` -------------------------------- ### Create and Animate a Tween with Chaining Source: https://github.com/tweenjs/tween.js/blob/main/examples/00_hello_world.html This snippet shows how to create a tween, define its target properties, duration, easing, and an update callback. It also demonstrates chaining tweens and managing them with a Group for animation. ```javascript import {Tween, Easing, Group} from '../dist/tween.esm.js' const position = {x: 100, y: 100, rotation: 10} const target = document.getElementById('target') const tween = new Tween(position) .to({x: 700, y: 200, rotation: 359}, 2000) .delay(1000) .easing(Easing.Elastic.InOut) .onUpdate(update) const tweenBack = new Tween(position) .to({x: 100, y: 100, rotation: 10}, 3000) .easing(Easing.Elastic.InOut) .onUpdate(update) tween.chain(tweenBack) // tweenBack.chain(tween) tween.start() const group = new Group(tween, tweenBack) animate(performance.now()) function animate(time) { group.update(time) // If the update method returns false, it means all tweens in // the group are done playing, so we can stop the loop. const keepGoing = !group.allStopped() if (keepGoing) requestAnimationFrame(animate) } function update() { target.style.transform = `translate3d(${position.x}px, ${position.y}px, 0.0001px) rotateY(${Math.floor( position.rotation, )}deg)` } ``` -------------------------------- ### Configure Tween Repetition Source: https://github.com/tweenjs/tween.js/blob/main/examples/08_repeat.html Demonstrates initializing multiple tweens with different repeat settings, including no repeat, a fixed count, and infinite looping. ```javascript import {Tween, Group, Easing} from '../dist/tween.esm.js' const group = new Group() init() animate() function init() { const target1 = document.getElementById('target1'), tween1 = new Tween(target1.dataset) .to({rotation: 360}, 1000) .easing(Easing.Exponential.InOut) .delay(100) .onUpdate(function (object) { updateBox(target1, object) }) .start(), target2 = document.getElementById('target2'), tween2 = new Tween(target2.dataset) .to({rotation: 360}, 1000) .easing(Easing.Exponential.InOut) .repeat(2) .delay(100) .onUpdate(function (object) { updateBox(target2, object) }) .start(), target3 = document.getElementById('target3'), tween3 = new Tween(target3.dataset) .to({rotation: 360}, 1000) .easing(Easing.Exponential.InOut) .repeat(Infinity) .delay(100) .onUpdate(function (object) { updateBox(target3, object) }) .start() group.add(tween1, tween2, tween3) } function animate(time) { requestAnimationFrame(animate) group.update(time) } function updateBox(box, params) { const s = box.style, transform = 'rotate(' + Math.floor(params.rotation) + 'deg)' s.webkitTransform = transform s.mozTransform = transform s.transform = transform } ``` ```css .box { width: 100px; height: 100px; margin: 10px; padding: 10px; display: inline-block; float: left; } #target1 { background: #fcc; } #target2 { background: #cfc; } #target3 { background: #ccf; } ``` -------------------------------- ### Load Tween.js from CDN Source: https://github.com/tweenjs/tween.js/blob/main/README.md Methods to load the UMD build of the library directly from a CDN. ```html ``` ```html ``` -------------------------------- ### Create and configure a basic tween Source: https://github.com/tweenjs/tween.js/blob/main/docs/user_guide.md This snippet shows how to create a new tween instance for a given object and specify the target properties and duration for the animation. ```javascript import {Tween} from '@tweenjs/tween.js' // Create a tween for position first const tween = new Tween(position) // Then tell the tween we want to animate the x property over 1000 milliseconds tween.to({x: 200}, 1000) ``` -------------------------------- ### Import Tween.js as ES6 Module Source: https://github.com/tweenjs/tween.js/blob/main/README.md Recommended method for importing the library using the ES6 module build. ```html ``` -------------------------------- ### Import Tween.js with Build Tools Source: https://github.com/tweenjs/tween.js/blob/main/README.md Use standard import syntax when working with bundlers like Webpack, Vite, or Rollup. ```javascript import * as TWEEN from '@tweenjs/tween.js' ``` -------------------------------- ### Configure Easing Functions Source: https://context7.com/tweenjs/tween.js/llms.txt Apply built-in easing equations, generate custom power curves, or define custom step-based easing functions. ```javascript import { Tween, Easing } from '@tweenjs/tween.js' const position = { x: 0 } // Built-in easing functions new Tween(position).to({ x: 100 }, 1000).easing(Easing.Linear.None).start() new Tween(position).to({ x: 100 }, 1000).easing(Easing.Quadratic.In).start() new Tween(position).to({ x: 100 }, 1000).easing(Easing.Elastic.Out).start() new Tween(position).to({ x: 100 }, 1000).easing(Easing.Bounce.InOut).start() new Tween(position).to({ x: 100 }, 1000).easing(Easing.Back.Out).start() // Generate custom power easing const customEasing = Easing.generatePow(3) // Cubic-like easing new Tween(position).to({ x: 100 }, 1000).easing(customEasing.InOut).start() // Custom easing function (step-based) function stepEasing(k) { return Math.floor(k * 5) / 5 // 5 discrete steps } new Tween(position).to({ x: 100 }, 1000).easing(stepEasing).start() ``` -------------------------------- ### Import Tween.js via UMD Source: https://github.com/tweenjs/tween.js/blob/main/README.md Deprecated method for importing the library using the UMD build. ```html ``` -------------------------------- ### Use window.performance.now() for smoother animations Source: https://github.com/tweenjs/tween.js/wiki/Old-change-log Enhances animation smoothness by utilizing `window.performance.now()` when available. This improvement was made in release r9. ```javascript Use window.performance.now() if available for even smoother animations ``` -------------------------------- ### Animate Box Position with Tween.js Source: https://github.com/tweenjs/tween.js/blob/main/examples/19_end_tween.html This snippet animates a box element's position from (0,0) to (300,200) over 5 seconds using Tween.js. It includes setup for the element, tween creation, easing, and updating the element's style in the onUpdate callback. Ensure the HTML element with id 'box' exists and the Tween.js library is imported. ```javascript import {Tween, Easing} from '../dist/tween.esm.js' const box = document.getElementById('box') // Get the element we want to animate. const coords = {x: 0, y: 0} // Start at (0, 0) const tween = new Tween(coords, false) // Create a new tween that modifies 'coords'. .to({x: 300, y: 200}, 5000) // Move to (300, 200) in 1 second. .easing(Easing.Quadratic.InOut) // Use an easing function to make the animation smooth. .onUpdate(() => { // Called after tween.js updates 'coords'. // Move 'box' to the position described by 'coords' with a CSS translation. box.style.setProperty('transform', 'translate(' + coords.x + 'px, ' + coords.y + 'px)') // console.log(coords, tween.isPlaying()) }) .onComplete(() => { console.log('onComplete') }) .start() // Start the tween immediately. // Setup the animation loop. function animate(time) { tween.update(time) requestAnimationFrame(animate) } requestAnimationFrame(animate) document.querySelector('#end').addEventListener('click', () => { console.log('tween.end') tween.end() console.log(tween) }) ``` -------------------------------- ### Animate 1000 Bars with Tween.js Source: https://github.com/tweenjs/tween.js/blob/main/examples/01_bars.html Initializes a TWEEN.Group and creates 1000 DOM elements that animate back and forth using chained tweens. ```javascript import * as TWEEN from '../dist/tween.esm.js' const group = new TWEEN.Group() const stats = new Stats() const sds = stats.domElement.style sds.position = 'absolute' sds.right = '0px' sds.top = '0px' sds.margin = '4em 3em' document.body.appendChild(stats.domElement) for (let i = 0; i < 1000; i++) { const startValue = 500 + (Math.random() - Math.random()) * 250 const endValue = 500 + (Math.random() - Math.random()) * 250 const domElement = document.createElement('div') const bg = (Math.random() * 0xffffff) >> 0 domElement.style.position = 'absolute' const y = Math.random() * window.innerHeight domElement.style.translate = startValue + 'px ' + y + 'px' domElement.style.background = '#' + bg.toString(16) domElement.style.width = '100px' domElement.style.height = '2px' const elem = {x: startValue, domElement: domElement, y} const updateCallback = function (object) { object.domElement.style.translate = object.x + 'px ' + object.y + 'px' } const tween = new TWEEN.Tween(elem) .to({x: endValue}, 4000) .delay(Math.random() * 1000) .onUpdate(updateCallback) .easing(TWEEN.Easing.Back.Out) .start() const tweenBack = new TWEEN.Tween(elem) .to({x: startValue}, 4000) .delay(Math.random() * 1000) .onUpdate(updateCallback) .easing(TWEEN.Easing.Elastic.InOut) tween.chain(tweenBack) tweenBack.chain(tween) group.add(tween, tweenBack) document.body.appendChild(elem.domElement) } animate() function animate(time) { requestAnimationFrame(animate) group.update(time) stats.update() } ``` -------------------------------- ### Initialize Tween from Global Variable Source: https://github.com/tweenjs/tween.js/blob/main/README.md Usage pattern for accessing Tween components after loading the UMD build. ```html ``` -------------------------------- ### Run Lint and Formatting Checks Source: https://github.com/tweenjs/tween.js/blob/main/docs/contributor_guide.md Automatically format code and report any style errors that cannot be automatically fixed. This ensures code style uniformity using Prettier and ESLint. ```bash npm run test-lint ```