Javascript Canvas:未捕获的TypeError

时间:2018-09-16 08:13:53

标签: javascript oop canvas html5-canvas javascript-objects

以下代码无法正常工作。引发以下错误:

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圆时,它将引发Uncaught TypeError: Cannot read property 'draw' of undefined at animatedrawCircle类中的函数)。

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

1 个答案:

答案 0 :(得分:0)

我希望这是您要实现的目标:

const canvas = document.getElementById("canvas");
const c = canvas.getContext("2d");
let cw = (canvas.width = window.innerWidth);
let ch = (canvas.height = window.innerHeight);

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.clearRect(0,0, cw,ch);
    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 >= cw || 
        this.x - this.radius <= 0) {
        this.dx = -this.dx;
    }
    if (this.y + this.radius >= ch || 
        this.y - this.radius <= 0) {
        this.dy = -this.dy;
    }
    this.y += this.dy;
    this.x += this.dx;

    this.draw();
  };
}

var circle = new Circle(200, 200, 5, 5, 30); //Circle is instantiated
var x = Math.random() * cw;
var y = Math.random() * ch;
var dx = (Math.random() - 0.5) * 8;
var dy = (Math.random() - 0.5) * 8;
var radius = 30;

function animate() {
  requestAnimationFrame(animate);

  circle.update();

  c.beginPath();
  c.arc(x, y, radius, 0.0, Math.PI * 2, false);
  c.strokeStyle = "blue";
  c.stroke();
}


animate()
<canvas id="canvas"></canvas>