Week4. Animation

W3c course - Week 4 animation.

by schrodingers

HTML

<script src="https://github.com/michaelvillar/dynamics.js/releases/download/0.0.7/dynamics.js"></script>
<canvas id="canvas">Hey you!</canvas>
<div class="buttons">
<button onclick="start()">Start</button>
<button onclick="stop()">Stop</button>
</div>

CSS

body {
    margin: 5em auto;
    display: flex;
    flex-flow: column wrap;
    align-items: center;
//    justify-content: space-between;
}

canvas {
    width: 50vh;
    height: 50vh;
    border: 1px solid black;
}

button:nth-of-type(1),
button:nth-of-type(2){
    position: relative;
    width: 5em;
    height: 2em;
    margin: 1em auto;
}

JavaScript

var rectangleX = 0;
var colors = ['crimson', 'dodgerblue', 'seagreen'];
var currentColor = 0;
var speed = 3;
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

/* ==== Animation methods: ======  */
// 1) setInterval(animate, 100); problem with debugging and multiply animations sync
// 2) setTimeout(animate, 100);
/* setTimeout will call the function only once, after a delay passed as second parameter. As setTimeout runs the function passed as the first parameter only once, in order to implement an animation loop, we have to call it again at the end of the loop.
 */
// 3) USE requestAnimationFrame(animate) for 60frames/sec;


requestAnimationFrame(animate);

function animate() {
// 1. Clear the canvas
    ctx.clearRect(0, 0, canvas.width, canvas.height);
// 2. Draw a figure
    ctx.fillStyle = 'dodgerblue';
    ctx.fillRect(rectangleX, 0, 100, 100);
    
// 3. Move figure
    rectangleX += speed;
    if((rectangleX+100 > canvas.width || rectangleX <= 0)) {
    speed = -speed;
    }
    requestAnimationFrame(animate);
}


  function start() {
         // Start the animation loop, change 20 for bigger values
         requestId = setInterval(animationLoop, 20);
     }
     function stop() {
         if (requestId) {
             clearInterval(requestId);
         }
     }