Javascript Canvas: Uncaught TypeError - PullRequest
       16

Javascript Canvas: Uncaught TypeError

0 голосов
/ 16 сентября 2018

Следующий код не работает должным образом. Выдается следующая ошибка:

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

1 Ответ

0 голосов
/ 16 сентября 2018

Я надеюсь, что это то, чего вы хотите достичь:

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>
...