JSFiddle - React, Tailwind, and code Playground

by FilipFlora

HTML

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title></title>
        <style type="text/css">
            body {
                background-color: #CCCCCC;
                overflow: hidden;
            }
            
            #index_canvas {
                width: 500px;
                height: 400px;
                position: absolute;
                left: 0px;
                top: 0px;
            }
        </style>
    </head>
        
    <body>
        <canvas width="500" height="400" id="index_canvas"></canvas>
    </body>
</html>

JavaScript

Math.rand = function (min, max) {
    return(Math.round(Math.random() * (max-min)) + min);
}
    
// animation object
var indexAnim = {
    images: [], // here are the image objects
    positions: [], // the actual positions of the images
    destPositions: [] // the target coordinates of the image
}

jQuery(document).ready(function() {
   
    // init (only 2 images for now)
    for( var i = 1; i<=2; i++) {
       
        // create a new image to place on canvas
        var im = new Image();
        im.src = 'http://phil.hu/Thinkrement/Canvas-active-bg/phil-0'+i+'.png';  
        indexAnim.images[i-1] = im;
        // place it randomly on canvas
        indexAnim.positions[i-1] = Array(Math.rand(-300, 300), Math.rand(-300, 300)); 
        // set it's destination positions
        indexAnim.destPositions[i-1] = Array(Math.rand(-300, 300), Math.rand( -300, 300));
    
    }
    
    // just for a better performance
    var length = indexAnim.images.length;
    var canvas = document.getElementById('index_canvas').getContext('2d');
    
    // let the animation begin (... WHA-HA-HAAA)
    setInterval(function () {
        
        // clear the image
        canvas.clearRect(0,0,500,400);  
        
        // let's redraw all the images
        for( var i = 0; i<length; i++ ) {
            
            // if a new target position is needed (either x or y)
            if( Math.abs(indexAnim.positions[i][0] - indexAnim.destPositions[i][0]) < i+1 || Math.abs(indexAnim.positions[i][1] - indexAnim.destPositions[i][1]) < i+1 ) {
                indexAnim.destPositions[i] = Array(Math.rand(0, 400), Math.rand( -300, 300));
            }
            
            // set the new position of the image. It's only 1 pixel closer to the destination coordinate (Just like in life...)
            indexAnim.positions[i][0] = indexAnim.positions[i][0] + (indexAnim.positions[i][0] < indexAnim.destPositions[i][0] ? 1: -1);
            indexAnim.positions[i][1] =...