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))代码>