简体   繁体   English

当我将对象作为参数传递时,JavaScript抛出:“不是函数”

[英]JavaScript throws: “is not a function” when I pass object as 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 a error occurs "ctx.clearRect is not a function" but when I get context from canvas in method animate instead of pass it as argument it's working. 当我运行此代码时出现错误“ctx.clearRect不是函数”但是当我从方法动画中的canvas获取上下文而不是将其作为参数传递时它正在工作。

You have to pass the ctx context on the next tick, otherwise the ctx argument is undefined , and undefined has no method clearRect 你必须在下一个tick上传递ctx上下文,否则ctx参数是undefinedundefined没有方法clearRect

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

FIDDLE 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM