JavaScript抛出:“引用;不是一个函数;当我将object作为参数传递时

JavaScript抛出:“引用;不是一个函数;当我将object作为参数传递时,javascript,Javascript,这是我的简单代码: 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

这是我的简单代码:

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);
}

当我运行此代码时,会出现一个错误“ctx.clearRect不是一个函数”,但当我在方法animate中从画布获取上下文而不是将其作为参数传递时,它会工作。

您必须在下一个勾号上传递
ctx
上下文,否则
ctx
参数是
未定义的
,而且
undefined
没有方法
clearect

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

requestAnimationFrame
调用
animate
函数时,
ctx
参数将不可用:
window.requestAnimationFrame(animate.bind(null,ctx))