Last active
March 11, 2016 17:11
-
-
Save bfgeek/fb40aeb569e1fc6276b3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Main thread. | |
window.compositorWorklet.import('parallax.js').then(function() { | |
// Library ready to use. | |
// This creates an instance of the CompositorAnimator class inside | |
// the worklet that we can communicate to. | |
const animator = new CompositorAnimator('parallax', {rate: 0.5}); | |
// Can postMessage directly to that instance. | |
// (We know that this is a bad way of setting up the compositor effect, | |
// but treat it as an example of postMessage working :), CompositorElementRef | |
// is a transferrable, and only exposes safe things in the worklet). | |
animator.postMessage({ | |
scroller: new CompositorElementRef(document.getElementById('scroller')), | |
parallax: new CompositorElementRef(document.getElementById('parallax')), | |
}); | |
// Can receive messages as well. | |
animator.addEventListener('message', function() { /* do something */ }); | |
}); | |
// parallax.js (inside worklet) | |
// Only need to extend from CompositorAnimator if we | |
// need postMessage back to the main thread. | |
registerCompositorAnimator(class extends CompositorAnimator { | |
constructor(options) { // Options is structured cloned across. | |
this.scroller = null; | |
this.parallax = null; | |
this.rate = options.rate || 0.1; | |
} | |
onmessage(data) { | |
this.scroller = data.scroller; | |
this.parallax = data.parallax; | |
} | |
// This is invoked by the compositor thread to update the parallax effect. | |
tick(timestamp) { | |
if (!this.scroller || !this.parallax) return; | |
const t = this.parallax.transform; | |
t.m42 = -this.rate * this.scroller.scrollTop; | |
this.parallax.transform = t; | |
// This would work only if extended from CompositorAnimator. | |
this.postMessage('ticked!'); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment