Js animation practice physics.js

Animations playground.

by schrodingers

HTML

<script src="https://github.com/michaelvillar/dynamics.js/releases/download/0.0.7/dynamics.js"></script>
 <h1>Js animation practice</h1>

<div class="circle"></div>
<div class="square"></div>
<div class="box"></div>
<div class="box"></div>

CSS

html, body {
    margin: 0;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}
body {
    margin: 0;
    padding: 0;
    display: flex;
    flex-flow: column;
    align-items: center;
    justify-content: center;
}
h1 {
    font: 2em/1.5'Roboto', sans-serif;
}
.box {
    width: 4em;
    height: 4em;
    background: lightseagreen;
    // position: absolute;
    background: #853e83;
}
.triangle {
    width: 4em;
    height: 4em;
    background: lightseagreen;
}
.circle {
    width: 4em;
    height: 4em;
    background: lightseagreen;
    border-radius: 100%;
}

JavaScript

var box = document.querySelector('.circle');
box.style.transform = 'translateX(-100px)';
box.style.webkitTransform = 'translateX(-100px)';
window.addEventListener('click', toggle);
window.addEventListener('touchstart', toggle);

var left = true;

var tween = {
    startTime: 0,
    startX: 0,
    endX: 0,
    duration: 0,
}

// easing function
var easeOutQuart = function (t, b, c, d) {
    t /= d;
    t--;
    return -c * (t * t * t * t - 1) + b;
};

function loop() {
    // get current time
    var t = Date.now() - tween.startTime;
    // make the update
    if (t <= tween.duration) {
        var translate = 'translateX(' + (easeOutQuart(t, tween.startX, tween.endX, tween.duration)) + 'px)';
        box.style.transform = translate;
        box.style.webkitTransform = translate;
    }

    requestAnimationFrame(loop);
}


function toggle() {
    // toggle the tween
    if (left) {
        left = false;
        tween.startTime = Date.now();
        tween.startX = -100;
        tween.endX = 200;
        tween.duration = 500;
    } else {
        left = true;
        tween.startTime = Date.now();
        tween.startX = 100;
        tween.endX = -200;
        tween.duration = 500;
    }
}

loop();

// TRIANGLE
var el = document.querySelectorAll('.triangle');

// From purple to green
function animate1() {
    dynamics.animate(el, {
        rotateZ: 180,
        scale: .5,
        borderBottomColor: '#43F086'
    }, {
        type: dynamics.spring,
        friction: 400,
        duration: 1300,
        complete: animate2
    });
}

// From green to purple
function animate2() {
    dynamics.animate(el, {
        rotateZ: 360,
        scale: 1,
        borderBottomColor: '#CA2F6F'
    }, {
        type: dynamics.spring,
        frequency: 600,
        friction: 400,
        duration: 1800,
        anticipationSize: 350,
        anticipationStrength: 400,
        complete: animate1
    });
}

// Start first animation
animate1();