【发布时间】:2023-03-05 21:32:01
【问题描述】:
在我的控制台中,我收到错误:“未捕获的 TypeError:无法读取属性 'getContext' of null” 我就是找不到我犯的错误……或者我做错了什么。 所以也许你可以帮我找到它? 请帮忙:)
enter code here
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var cW = canvas.width = 1000;
var cH = canvas.height = 500;
var particleAmount = 10;
var particles = [];
for(var i=0;i<particleAmount;i++) {
particles.push(new particle());
}
function particle() {
this.x = (Math.random() * (cW-(40*2))) + 40;
this.y = (Math.random() * (cH-(40*2))) + 40;
this.xv = Math.random()*20-10;
this.yv = Math.random()*20-10;
}
function draw () {
ctx.fillStyle = "black";
ctx.fillRect(0,0,cW,cH);
for(var ii=0;ii<particles.length;ii++){
var p = particles[ii];
ctx.fillStyle = "red";
ctx.beginPath();
ctx.arc(p.x,p.y,40,Math.PI*2,false);
ctx.fill();
}
}
setInterval(draw,30);
【问题讨论】:
-
您确定要在 DOM 准备就绪时加载脚本吗?
-
这是我的 html 代码:
Vector_5 html> -
对,所以画布还不存在。在画布元素之后加载脚本。
-
谢谢!! :D 现在可以正常使用了!
标签: javascript particles