【发布时间】:2019-02-20 11:07:58
【问题描述】:
以下代码无法正常工作。抛出以下错误:
Uncaught TypeError: Cannot read property 'draw' of undefined at animate
Circle类:
function Circle(x, y, dx, dy, radius) {
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.radius = radius;
this.draw = function() {
c.beginPath();
c.arc(this.x, this.y, this.radius, 0, Math.PI*2, false);
c.strokeStyle = "#ff0000";
c.stroke();
}
this.update = function() {
if (this.x+this.radius >= innerWidth || this.x-this.radius <= 0) {
this.dx =- this.dx;
}
if (this.y + this.radius >= innerHeight || this.y - this.radius <= 0) {
this.dy =- this.dy;
}
this.y = this.y + this.dy;
this.x = this.x + this.dx;
this.draw();
}
}
类的实例已创建:
var circle = new Circle(200, 200, 5, 5, 30); //Circle is instantiated
var x = Math.random() * window.innerWidth;
var y = Math.random() * window.innerHeight;
var dx = (Math.random() - 0.5)*8;
var dy = (Math.random() - 0.5)*8;
var radius =30;
动画功能:
该函数中使用var circle时,抛出Uncaught TypeError: Cannot read property 'draw' of undefined at animate(draw是Circle类中的一个函数)。
function animate() {
requestAnimationFrame(animate);
circle.draw(); // Error
c.beginPath();
c.arc(x,y,radius,0.0,Math.PI*2,false);
c.strokeStyle="blue";
c.stroke();
}
【问题讨论】:
-
当您调用
circle.draw时,听起来circle是未定义的。您可以发布您在var circle的位置以及animate在您的代码中的位置吗?
标签: javascript oop canvas html5-canvas javascript-objects