JavaScript throws: "not a function" when I pass an object as an argument

This is my simple code:

var x = 0, y = 0;

function start() {
    var canvas = document.getElementById("myCanvas"), ctx = canvas.getContext("2d");

    animate(ctx);
}

function animate(ctx) {
    ctx.clearRect(0,0,500,500);
    ctx.fillRect(x, y, 20, 20);
    ctx.save();
    x++;
    window.requestAnimationFrame(animate);
}

When I run this code, the error "ctx.clearRect is not a function" occurs, but when I get the context from the canvas in the animate method, instead of passing it as an argument, it works.

+4
source share
1 answer

You need to transfer the context of ctxthe next tick, or an argument ctx undefined, and undefineddoes not have a methodclearRect

function animate(ctx) {
    ctx.clearRect(0,0,500,500);
    ctx.fillRect(x, y, 20, 20);
    ctx.save();
    x++;
    window.requestAnimationFrame(function() {
        animate(ctx);
    });
}

Fiddle

+7
source

Source: https://habr.com/ru/post/1584885/


All Articles