Giter Club home page Giter Club logo

dynamics.js's Introduction

Dynamics.js

Dynamics.js is a JavaScript library to create physics-based animations

To see some demos, check out dynamicsjs.com.

Usage

Download:

Include dynamics.js into your page:

<script src="dynamics.js"></script>

You can animate CSS properties of any DOM element.

var el = document.getElementById("logo")
dynamics.animate(el, {
  translateX: 350,
  scale: 2,
  opacity: 0.5
}, {
  type: dynamics.spring,
  frequency: 200,
  friction: 200,
  duration: 1500
})

You also can animate SVG properties.

var path = document.querySelector("path")
dynamics.animate(path, {
  d: "M0,0 L0,100 L100,50 L0,0 Z",
  fill: "#FF0000",
  rotateZ: 45,
  // rotateCX and rotateCY are the center of the rotation
  rotateCX: 100,
  rotateCY: 100
}, {
  friction: 800
})

And any JavaScript object.

var o = {
  number: 10,
  color: "#FFFFFF",
  string: "10deg",
  array: [ 1, 10 ]
}
dynamics.animate(o, {
  number: 20,
  color: "#000000",
  string: "90deg",
  array: [-9, 99 ]
})

Reference

dynamics.animate(el, properties, options)

Animates an element to the properties with the animation options.

  • el is a DOM element, a JavaScript object or an Array of elements
  • properties is an object of the properties/values you want to animate
  • options is an object representing the animation
    • type is the animation type: dynamics.spring, dynamics.easeInOut,... (default: dynamics.easeInOut)
    • frequency, friction, bounciness,... are specific to the animation type you are using
    • duration is in milliseconds (default: 1000)
    • delay is in milliseconds (default: 0)
    • complete (optional) is the completion callback
    • change (optional) is called at every change. Two arguments are passed to the function. function(el, progress)
      • el is the element it's animating
      • progress is the progress of the animation between 0 and 1

dynamics.stop(el)

Stops the animation applied on the element

dynamics.css(el, properties)

This is applying the CSS properties to your element with the correct browser prefixes.

  • el is a DOM element
  • properties is an object of the CSS properties

dynamics.setTimeout(fn, delay)

Dynamics.js has its own setTimeout. The reason is that requestAnimationFrame and setTimeout have different behaviors. In most browsers, requestAnimationFrame will not run in a background tab while setTimeout will. This can cause a lot of problems while using setTimeout along your animations. I suggest you use Dynamics's setTimeout and clearTimeout to handle these scenarios.

  • fn is the callback
  • delay is in milliseconds

Returns a unique id

dynamics.clearTimeout(id)

Clears a timeout that was defined earlier

  • id is the timeout id

dynamics.toggleSlow()

Toggle a debug mode to slow down every animations and timeouts. This is useful for development mode to tweak your animation. This can be activated using Shift-Control-D in the browser.

Dynamics and properties

dynamics.spring

  • frequency default is 300
  • friction default is 200
  • anticipationSize (optional)
  • anticipationStrength (optional)

dynamics.bounce

  • frequency default is 300
  • friction default is 200

dynamics.forceWithGravity and dynamics.gravity

  • bounciness default is 400
  • elasticity default is 200

dynamics.easeInOut, dynamics.easeIn and dynamics.easeOut

  • friction default is 500

dynamics.linear

No properties

dynamics.bezier

  • points array of points and control points

The easiest way to output this kind of array is to use the curve creator. Here is an example:

[{"x":0,"y":0,"cp":[{"x":0.2,"y":0}]},
 {"x":0.5,"y":-0.4,"cp":[{"x":0.4,"y":-0.4},{"x":0.8,"y":-0.4}]},
 {"x":1,"y":1,"cp":[{"x":0.8,"y":1}]}]

Contributing

Compile: npm run build or npm run build:watch

Run tests: npm test

Browser Support

Working on

  • Safari 7+
  • Firefox 35+
  • Chrome 34+
  • IE10+

Sylvester

Some code from Sylvester.js has been used (part of Vector and Matrix).

License

The MIT License (MIT)

Copyright (c) 2015 Michael Villar

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

dynamics.js's People

Contributors

djfrsn avatar grafikart avatar michaelvillar avatar mv-stripe avatar perrin4869 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dynamics.js's Issues

SVG Rotation Transforms are "funny"

I'm sure this has nothing to do with dynamics.js (which is great btw). I've found that when rotating an svg, if the rotation is a multiple of 360 it won't rotate at all. In some cases, when the rotation is say 270 degrees, the rotation will actually happen in reverse. I'm thinking svgs have some funky polar coordinates , but I haven't found any documentation explaining the issue.

I've gotten around the issue by using css transforms, although I'm not sure this is ideal.

I've illustrated the behavior here:
http://codepen.io/ipetepete/pen/doZqxK

I just wanted to report my findings for others. If anybody knows how to make svg rotation transforms work properly, I'd love to hear how.

rotateX

Hello,

I'm just playing around with your nice library...
very cool!

but is it somehow possible to rotate arround the x axis?

rotateX has no effect.

Older browsers `document.visibilityState`

For example Android 4.4 doesn't supports document.visibilityState without the webkit prefix, creating an animation with a delay will never be triggered on these devices because isDocumentVisible will not return false.
Is it an idea to check for 'visibilityState' in document and then return the document visibility or true for older browsers?

Uncaught TypeError: Cannot read property 'length' of undefined

Can't seem to get this to work properly, seem to be doing everything right from what I can see in the docs.

Uncaught TypeError: Cannot read property 'length' of undefined
    at t.interpolate (dynamics.min.js:1)
    at t.interpolate (dynamics.min.js:1)
    at q (dynamics.min.js:1)
    at m (dynamics.min.js:1)
    at P (dynamics.min.js:1)
var block = $('.feature-block');
var path = $('#feature-path');
block.data('dragging', false);
block.data('c', { x: 100, y: 10 });
block.data('start', { x: 0, y: 0 });

function update() {
    var dy = block.data('c').y - 10;
    var dampen = dy > 0 ? 2 : 4;

    block.css('transform', 'translate3d(0,' + dy / dampen + 'px,0)');
    path.attr('d', 'M0,100 L100,100 L100,10 ' + 'Q' + block.data('c').x + ',' + block.data('c').y + ' 0,10');
}
update();

block.on('mousedown', function(e) {
    e = e.changedTouches ? e.changedTouches[0] : e;
    var $this = $(this);
    $this.data('dragging', true);
    $this.data('start').x = e.pageX;
    $this.data('start').y = e.pageY;
});

$(document).on('mousemove', function(e) {
    e = e.changedTouches ? e.changedTouches[0] : e
    if (block.data('dragging') && ((e.pageY - block.position().top > -200 && e.pageY - block.position().top <= 0) || (e.pageY - block.position().top < 250 && e.pageY - block.position().top >= 0))) {
      block.data('c').x = (50 + (e.pageX - block.data('start').x)/block.width())
      // dampen vertical drag by a factor
      var dy = e.pageY - block.data('start').y
      var dampen = dy > 0 ? 20 : 20
      block.data('c').y = 10 + dy / dampen
      update();
    }
});

$(document).on('mouseup', function(e) {
    if (block.data('dragging')) {
      block.data('dragging', false);
      dynamics.animate(path, {
        x: 100,
        y: 100
      }, {
        type: dynamics.spring,
        duration: 700,
        friction: 280,
        change: update
      })
    }
});

add support for css filters

Unless I missed the part in the docs that mentions how to interpolate custom props or how to handle filters.

[NEED HELP] Need your help, @michaelvillar!

Hi @michaelvillar
I used matrix compose/decompose from you dynamics.js, and my tweening engine is another type. All works fine, including IE9, also gets all current style back to IE9!
But in all browser rotateZ doesn't work properly, i seen in your demo site all works fine, please help.

  • I will keep dynamics.js link in tweening engine my source used list

Sorry for my english

Why % css doesn't work

I try to use css percent value and the result is bad. The animate func try to animate to the value, if you put 50% on a width for example, it will translate to 50px and in the end of animation set 50%. Strange result

Allow to fake dom elemenst with js objects

something like this

var fakeSvgObj = {
    d: "...",
    fill: "....",
    _objectType: "SVG"
}

dynamics.animate(fakeSvgObj, {
    d: "M0,0 L0,100 L100,50 L0,0 Z",
    fill: "#FF0000",
    rotateZ: 45,
    // rotateCX and rotateCY are the center of the rotation
    rotateCX: 100,
    rotateCY: 100
}, {
    friction: 800
})

then it will try the object like a svg. ( is this possible?)

why? it will integrate nicely with the vdom libraries out there, like reactjs and mercury, etc. and let the dom changes to these library instead of be done by dynamics.js itself.

because currently the library is supported in browsers where is possible create objects with with getter and setter functions, will be easy to communicate the changes to mercuryjs for example and fire the re-render functionality. without conflict with the library.

Some strange error occured

I've been writing some tests and got some error occured in karma test Chrome environment.

var $elem = document.querySelector('.message');
dynamics.animate($elem, {
    scale: 1.5
  }, {
    type: dynamics.bounce,
    frequency: 450,
    friction: 200,
    duration: 1000
})

Will raise following error in karma Chrome:

Uncaught TypeError: Cannot read property '0' of undefined
    DecomposedMatrix.interpolate @ index.js:17591
    __bind @ index.js:16817
    interpolate @ index.js:18198
    animationTick @ index.js:18181
    runLoopTick @ index.js:18149

It fails on the following line src/dynamics.coffee#L495

decomposed[k][i] = (decomposedB[k][i] - decomposedA[k][i]) * t + decomposedA[k][i];

I've dived into code and find that it's because decomposedB.transform is false, so decomposedB['transform'][0] cannot be evaulated.

The decomposedB is set to false in startAnimation with following line:

endProperties['transform'] = matrix.decompose(); 

matrix is created with

matrix = Matrix.fromTransform(Matrix.matrixForTransform(v));

v is "scaleX(1.5) scaleY(1.5) scaleZ(1.5)"

And later matrix.decompose() returns false because of this statement:

if (els[3][3] === 0) {
  return false;
}

So if this is normal, then problem with some if statement in for cycle:

if !only? or only.indexOf(k) > -1 or only.indexOf("#{k}#{['x','y','z'][i]}") > -1

In original non karma environment everything works fine, but few conditions is not the same.

Uncaught TypeError: Cannot read property 'format' of null

I tried using this code. It seems to be working well on safari but triggers an error on chrome and the other browers. Is there an extra set up needed?

var dots = document.querySelectorAll('.dot')
var colors = ['#007EFF', '#FF3700', '#92FF00']

// Start the 3 dot animations with different delays
function animateDots() {
for(var i=0; i<dots.length; i++) {
dynamics.animate(dots[i], {
translateY: -70,
backgroundColor: colors[i]
}, {
type: dynamics.forceWithGravity,
bounciness: 800,
elasticity: 200,
duration: 2000,
delay: i * 450
})
}

dynamics.setTimeout(animateDots, 2500)
}

animateDots()

Complete callback not correct?

I'm trying to use dynamics.js and in my example i'm using it with hammer.js.

Everything works so far, but the complete-callback fires when animate starts, not when it ends.

I have the example on codepen
Codpenexample

Do i do something wrong or is it a bug?

animate background on chrome not working.

Hello there,

First of all i would like to express my gratitude for this amazing library, also I'm a big fan of your work.

I was playing around with dynamics.js for the first time and noticed that my code does not work on chrome, but does on firefox, the code that throws the error is the following:

dynamics.animate(el, {
      background: "red"
});

the error is the following:

Uncaught TypeError: Cannot read property 'rgb' of undefined
    at e.interpolate (dynamics.min.js:1)
    at e.interpolate (dynamics.min.js:1)
    at t.interpolate (dynamics.min.js:1)
    at t.interpolate (dynamics.min.js:1)
    at q (dynamics.min.js:1)
    at m (dynamics.min.js:1)
    at P (dynamics.min.js:1)

I'm Not sure if it's something that I'm doing wrong, if yes then i can't figure it out.

Element jumps back to original position

I'm animating a div block to the center of the screen. I've calculate the amount of pixels it should move to the left with translateX. It works. But, when the next animation on that element begins, it snaps back to its original position. The translateX is overwritten or something when 'fade card out' begins, it doesn't stay center screen.

// animate to center
        dynamics.animate(activeCard, {
            translateX: animateCards
        }, {
            type: dynamics.spring,
            friction: 400,
            duration: 1300,
            delay: 600
        });

        // fade card out
        dynamics.animate(activeCard, {
            scale: 1.2,
            opacity: 0
        }, {
            type: dynamics.spring,
            friction: 400,
            duration: 1300,
            delay: 1200
        });

How can I fix the position of this element after i've animated it?

Integrating with React

Hi Michael,
I liked so much dynamics.js and i've been playing around with it for a while.

I have been trying to implement an integration with React and I think I found a pretty easy and smart way to do it.

You should really check this out from my gist!

This could be the next Famo.us ;)

React and Dynamics integration concept

Bower support

This will help people a lot because many use bower to handle frontend plugins.

Dynamics.js Uncaught TypeError for arguments.callee in strict mode.

Hello Michael,

I've run into an issue using Dynamics.js in React component's with strict mode and ES6 classes. Using methods such as spring which use arguments.callee.defaults throw TypeErrors's. To solve this, I change the arguments.callee to the following format(dynamics.methodName.defaults) in order to avoid errors in my project. Is this something you would be interested in changing or having a pull request for?

Error Message:
Uncaught TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them

Example Solution for 'spring' method:
applyDefaults(options, arguments.callee.defaults);
now
applyDefaults(options, dynamics.spring.defaults);

Source:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee

Weird Issue Animating Object Propery

I have the following code:
dynamicsweirdness1
which, should, in theory, animate the zoom property on the Camera object to the specified value. However, the behavior I'm seeing is very strange where only the first few frames animate and then it spends the rest of the duration setting the value to the end value:
dynamicsweirdness2
This seems like a bug, but if perhaps I'm doing this incorrectly, please let me know.

some advices

some advices:
1: add samples to repo not just on website page
2: add some tests to codepen
3: integrate with angularjs/reactjs or any popular FE projects.

Init position

There could be an attribute to define the position of early x or y.

What do you think?

Thank you.

Transition in background tab

Seems like transition doesn't continue if the tab becomes inactive. I suppose this is the browser thing, but is there a way to get around this?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.