Duarte Arribas
Duarte Arribas

Reputation: 317

How to animate the canvas with js

I'm trying to make an animation using html canvas, but I don't know if I have the best approach to it.

What I'm trying is to make a <canvas id="canvas"></canvas> and draw a rectangle on it using the fillRect().

Then I'm executing a function onload, that has a timeout of 500 miliseconds.

The function basically draws the rectangle 1px to where I want, by changing its x or y, and then, with clearRect(), I'm crealing the rectangle some time after starting on the starting point and following the other one.

Am I doing this right? or is there a better way to approach it?

Upvotes: 0

Views: 848

Answers (2)

Faiz Khan
Faiz Khan

Reputation: 298

You can use this structure

const canvas = document.getElementById('can');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
canvas.style.backgroundColor = 'white';

var someconstructorName = function(paramA,paramB,...){
    "Initialisation of variables and other things"   

    this.draw = function(){
        "your logic"
    }

    this.update = function(){
        "your update logic"
        this.draw();
    }
}

function animate(){
    requestAnimationFrame(animate)

}
animate();

Check out this Pen here it will give you a good idea: https://codepen.io/khanChacha/pen/YgpBxM

Upvotes: 2

NeonNatureEX
NeonNatureEX

Reputation: 497

If you have to use this style multiple times, I recommend diving into AnimeJS, a JS library which makes animating a lot simpler. ^^

AnimeJS

It supports delays and timelines too, which seems to be what you are using right now ^^

Upvotes: 1

Related Questions