我几乎没有JS经验(我主要使用C#编程)。我正在尝试在html5画布中创建圆圈(星形)的随机布局,并且让它们以随机的x和y速度移动。我创建了一个Star
类来制作许多此类对象并对其进行操作,但是当我调用Update()
方法时,会收到以下TypeError:
TypeError: Cannot read property 'Update' of undefined
at animate (file:///F:/Code/Website/main.js:67:20)
at file:///F:/Code/Website/main.js:71:1
以下是引发错误的代码:
//Circle object
class Star
{
constructor(X, Y, VX, VY, R)
{
this.x = X;
this.y = Y;
this.vx = VX;
this.vy = VY;
this.r = R;
}
draw() {
c.beginPath();
c.arc(this.x, this.y, this.r, 0, Math.PI * 2, false);
c.strokeStyle = "blue";
c.stroke();
};
Update() {
if (this.x + this.r > pageWidth || this.x - this.r < 0) {
this.vx = -this.vx;
}
if (this.y + this.r > pageHeight || this.y - this.r < 0) {
this.vy = -this.vy;
}
//add velocity
this.x += this.vx;
this.y += this.vy;
this.draw();
};
}
for (var i = 0; i < 50; i++) {
var x = Math.random() * canvas.width;
var y = Math.random() * canvas.height;
var vx = Math.random();
var vy = Math.random();
var radius = 30;
let star = new Star(x, y, vx, vy, radius);
starArr.push(star);
}
console.log(starArr);
function animate() {
"use strict";
window.requestAnimationFrame(animate);
c.clearRect(0, 0, pageWidth, pageHeight);
for (var j = 0; j < starArr.length; j++); {
starArr[j].Update();
}
}
animate();
答案 0 :(得分:2)
在for循环上有一个错字,它调用Update方法:一个额外的分号;
for (var j = 0; j < starArr.length; j++); {
const canvas = document.querySelector("canvas");
const c = canvas.getContext("2d");
let pageWidth = canvas.width = window.innerWidth;
let pageHeight = canvas.height = window.innerHeight;
let starArr = []
//Circle object
class Star{
constructor(X, Y, VX, VY, R){
this.x = X;
this.y = Y;
this.vx = VX;
this.vy = VY;
this.r = R;
}
draw() {
c.beginPath();
c.arc(this.x, this.y, this.r, 0, Math.PI * 2, false);
c.strokeStyle = "blue";
c.stroke();
};
Update() {
if (this.x + this.r > pageWidth || this.x - this.r < 0) {
this.vx = -this.vx;
}
if (this.y + this.r > pageHeight || this.y - this.r < 0) {
this.vy = -this.vy;
}
//add velocity
this.x += this.vx;
this.y += this.vy;
this.draw();
};
}
for (var i = 0; i < 50; i++) {
var x = Math.random() * canvas.width;
var y = Math.random() * canvas.height;
var vx = Math.random();
var vy = Math.random();
var radius = 30;
let star = new Star(x, y, vx, vy, radius);
starArr.push(star);
}
function animate() {
//"use strict";
window.requestAnimationFrame(animate);
c.clearRect(0, 0, pageWidth, pageHeight);
for (var j = 0; j < starArr.length; j++) {
starArr[j].Update();
}
}
animate();
<canvas></canvas>