[英]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
参数是undefined
, undefined
没有方法clearRect
function animate(ctx) {
ctx.clearRect(0,0,500,500);
ctx.fillRect(x, y, 20, 20);
ctx.save();
x++;
window.requestAnimationFrame(function() {
animate(ctx);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.