我在html / canvas / javascript中使用小粒子系统。我在运行时遇到未定义的画布属性问题。
当我测试它时,我收到此错误:"未捕获TypeError:无法读取属性' clearRect'未定义"。似乎是功能" draw()"这会以某种方式导致错误。
无法弄清楚原因。有什么建议吗?
代码:
class Particle {
constructor(x,y,r,d) {
this.colors = ['#a14b79', '#79a14b', '#4ba19e'];
this.color = this.colors[Math.floor(Math.random() * 3)];
this.x = x;
this.y = y;
this.r = r;
this.d = d;
}
}
class Emitter {
constructor(amount) {
this.amount = amount;
this.canvas = document.getElementById('c');
this.context = this.canvas.getContext('2d');
this.width = window.innerWidth;
this.height = window.innerHeight;
this.canvas.width = this.width;
this.canvas.height = this.height;
this.particles = [];
this.angle = 0;
this.populate();
}
populate() {
for(var i = 0; i < this.amount; i++) {
this.particles.push(new Particle(Math.random()*this.canvas.width,Math.random()*this.canvas.height,Math.random()*15,Math.random()*this.amount));
}
setInterval(this.draw,33);
}
draw() {
this.context.clearRect(0,0,this.canvas.width,this.canvas.height);
this.context.beginPath();
for(var i = 0; i < this.particles.length; i++) {
var p = this.particles[i];
this.context.moveTo(p.x, p.y);
this.context.arc(p.x, p.y, p.r, 0, Math.PI*2, true);
this.context.fillStyle = p.color;
}
this.context.fill();
this.update();
}
update() {
this.angle += 0.01;
for(var i = 0; i < this.particles.length; i++) {
var p = this.particles[i];
p.y += Math.cos(this.angle+p.d) + 1 + p.r/2;
p.x += Math.sin(this.angle) * 2;
if(p.x > this.canvas.width+5 || p.x < -5 || p.y > this.canvas.height) {
if(i%3 > 0) {
this.particles[i] = {x: Math.random()*this.canvas.width, y: -10, r: p.r, d: p.d};
} else {
if(Math.sin(this.angle) > 0) {
this.particles[i] = {x: -5, y: Math.random()*this.canvas.height, r: p.r, d: p.d};
} else {
this.particles[i] = {x: this.canvas.width+5, y: Math.random()*this.canvas.height, r: p.r, d: p.d};
}
}
}
}
}
}
window.onload = function() {
const emitter = new Emitter(150);
};