K
K
kodwi2016-04-11 01:00:48
Canvas
kodwi, 2016-04-11 01:00:48

Why does the trail remain during animation?

function draw_obj(obj, ctx) {
    if (obj.drawn == true) {
        ctx.clearRect(obj.coord_x,  obj.coord_y,
                             obj.width, obj.height);
    }

    switch (obj.draw_type) {
        case cfg.draw_types.PLAYER:
            ctx.beginPath();

            ctx.rect(obj.coord_x, obj.coord_y, obj.width, obj.height);

            ctx.closePath();
            ctx.fillStyle = obj.filling;
            ctx.fill();

            break;
    }

    requestAnimationFrame(function() {draw_obj(obj, ctx);});

    obj.drawn = true;
    obj.coord_y += obj.speed;
}

In theory, before each drawing, the rectangle should be cleared, but in reality, a similar trail remains at any speed:
d816b34cff0e42f3ab0a76d2884b7ad5.png
What am I doing wrong?
UPD:
I found the problem, rewrote it like this:
function draw_obj(obj, ctx) {
    if (obj.drawn == true) {
        ctx.clearRect(
            obj.coord_x,
            obj.coord_y,
            obj.width,
            obj.height);
    }

    obj.coord_y += obj.speed;
    obj.coord_x += obj.speed;
    obj.drawn = true;

    ctx.beginPath();

    ctx.rect(obj.coord_x, obj.coord_y, obj.width, obj.height);

    ctx.closePath();
    ctx.fillStyle = obj.filling;
    ctx.fill();

    requestAnimationFrame(function() {draw_obj(obj, ctx);});
}

Still the loop:
ccd9cea89684481d843032d9fd608ad9.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
kodwi, 2016-04-11
@kodwi

The problem was in the zoomed canvas page. Reset to 100% and everything is ok.

G
GreatRash, 2016-04-11
@GreatRash

Why not clear the entire canvas?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question