Sunday 15 July 2018

TweenJS and Canvas Basic Sample

I've been playing around a bit more with animations on the HTML5 Canvas. While in this previous sample I was doing the basic movement logic myself, for this new experiment I wanted to use some library that would allow me to use easing equations. After some basic investigation I've opted for tweenJS. I'm not animating DOM elements, but shapes that I draw on the canvas, so I needed a library that would accept any object and update its values on request based on the selected movement/evolution logic, and then I would take care of drawing it. TweenJS fits perfectly into this mindset.

As in the previous sample, I'm leveraging the power of async/await to make it simple to launch my animations in sequence. There is not much to explain, just launch your debugger to see the typescript code.

while (true){
        for (let y=0; y<itemsMatrix.length; y++){
            for (let x=0; x<itemsMatrix[y].length; x++){
                let item:TweenJSSquare = itemsMatrix[y][x];
                await item.animateDiagonal(new Vector(canvas.width - ((x + 1) * size), size * y )); //endPosition:Vector,);
            }
        }

        for (let y=0; y<itemsMatrix.length; y++){
            for (let x=0; x<itemsMatrix[y].length; x++){
                let item:TweenJSSquare = itemsMatrix[y][x];
                await item.animateFall(canvas.height - (size * (y + 1)));
            }
        }

        for (let y=0; y<itemsMatrix.length; y++){
            for (let x=0; x<itemsMatrix[y].length; x++){
                let item:TweenJSSquare = itemsMatrix[y][x];
                await item.animateDiagonal(new Vector((x * size), size * y )); //endPosition:Vector,);
            }
        }
    
        for (let y=0; y<itemsMatrix.length; y++){
            for (let x=0; x<itemsMatrix[y].length; x++){
                let item:TweenJSSquare = itemsMatrix[y][x];
                await item.animateFall(canvas.height - (size * (y + 1)));
            }
        }
    }

No comments:

Post a Comment