How to make a Javascript animation with Canvas?

Asked

Viewed 79 times

-1

How do you make a small animation in Javascript? I tried to do so but it didn’t work:

var tela = document.querySelector('canvas');
    var pincel = tela.getContext('2d');
    pincel.fillStyle = 'lightgray';
    pincel.fillRect(0, 0, 600, 400);

    function desenhaCirculo(x, y, raio) {

        pincel.fillStyle = 'blue';
        pincel.beginPath();
        pincel.arc(x, y, raio, 0, 2 * Math.PI);
        pincel.fill();
    }

    function limpaTela() {

        pincel.clearRect(0, 0, 600, 400);
    }

    var x = 20;

    var sentido = 1;

    function atualizaTela() {



        if( x > 580) {
            sentido = -1;
        } else if (x < 20) {
            sentido = 1;
        } 

        desenhaCirculo(x, 20, 10);
        x = x + sentido;
    }

    setInterval(atualizaTela, 1);
<canvas width="600" height="400"></canvas>

1 answer

2

I guess you just forgot to put the limpaTela(); at the beginning of the function desenhaCirculo. Click on the blue button Execute downstairs:

var tela = document.querySelector('canvas');
var pincel = tela.getContext('2d');
pincel.fillStyle = 'lightgray';
pincel.fillRect(0, 0, 600, 400);

function desenhaCirculo(x, y, raio) {
    limpaTela();
    pincel.fillStyle = 'blue';
    pincel.beginPath();
    pincel.arc(x, y, raio, 0, 2 * Math.PI);
    pincel.fill();
}

function limpaTela() {

    pincel.clearRect(0, 0, 600, 400);
}

var x = 20;

var sentido = 1;

function atualizaTela() {



    if( x > 580) {
        sentido = -1;
    } else if (x < 20) {
        sentido = 1;
    } 

    desenhaCirculo(x, 20, 10);
    x = x + sentido;
}

setInterval(atualizaTela, 1);
<canvas width="600" height="400"></canvas>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.