HTML5的问题'for'循环,还有飞机
Problems with HTML5, 'for' loops, and airplanes
我正在创建的网页有更多的麻烦。我真的不知道怎么了。我认为这可能与我的"for"循环有关,但我不确定。我试图得到一个随机的图像动画横跨画布从一个随机的x位置开始。我将它设置为随机图像将从随机位置开始,但它不会移动。如果有人不介意看一眼,那就太好了。只是想让你知道,这个问题可能有一个非常简单的答案(来源:我很累)。谢谢你的宝贵时间
<html>
<head>
<style>
</style>
<script>
var airplaneArray = [];
function draw(){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var monoRed = document.getElementById('monoRed');
var biRed = document.getElementById('biRed');
var jet = document.getElementById('jet');
var biBlue = document.getElementById('biBlue');
var imageArray = [monoRed,biRed,jet,biBlue];
function plane(x,y,xspeed,yspeed,source,size){
this.x = x;
this.y = y;
this.xspeed = xspeed;
this.yspeed = yspeed;
this.source = source;
this.size = size;
}
plane.prototype.draw = function(){
ctx.drawImage(this.source,this.x,this.y,this.size,this.size);
}
plane.prototype.move = function(){
this.x += this.xspeed;
}
while(airplaneArray.length-1 < 5){
airplaneArray.push(new plane(Math.floor(Math.random()*1000),100,1,1,imageArray[Math.floor(Math.random()*4)],100),0);
}
ctx.save();
ctx.clearRect(0,0,1000,500);
ctx.fillStyle = 'rgba(200,0,0,1)';
ctx.fillRect(10,10,10,10);
for(i=0; i < airplaneArray.length; i++){
airplaneArray[i].draw();
airplaneArray[i].move();
}
ctx.restore();
var loopTimer = setTimeout('draw('+x+','+y+')',30);
}
</script>
</head>
<body onload="draw()">
<canvas id="canvas" width="1000" height="500"></canvas>
<img id="monoRed" src="http://www.vaachapter11.com/images/monoplane-red.png" width="0" height="0" alt="hi" />
<img id="biRed" src="http://www.vaachapter11.com/images/Biplane-Red.png" width="0" height="0" />
<img id="jet" src="http://www.vaachapter11.com/images/Jet-screaming.png" width="0" height="0" />
<img id="biBlue" src="http://www.vaachapter11.com/images/Biplane-blue.png" width="0" height="0" />
</body>
</html>
代码中的两个问题:
- 从
airplaneArray.push(new plane(Math.floor(Math.random()*1000),100,1,1,imageArray[Math.floor(Math.random()*4)],100),0);
中移除,0
- 将setTimeout更改为
setTimeout('draw()',30);
我的一些小评论:
-
<script>
标签应放在</body>
标签之前。 - 将所有的声明和数据准备移出
draw()
函数 - 应该改进你的算法来改变每个飞机的速度。示例:
airplaneArray.push(new plane(Math.floor(Math.random()*1000),100,Math.floor(Math.random()*20)+1,1,imageArray[Math.floor(Math.random()*4)],100));
相关文章:
- jQuery:循环一个具有不同超时值的循环
- 在循环中分配json值时,值被覆盖
- 如何在下面的ES6循环中获得前面的文本
- 为什么“;未定义的“;在JavaScript中结束循环
- Javascript循环不会自我更新
- 如何使用jquery处理php循环通过元素
- 而循环只设置php中输入字段中的第一个值
- 循环遍历数组中的特定索引
- Javascript返回值只在循环中返回一次
- 按照选项卡索引的顺序循环一个jQuery选择
- 循环遍历以数组为值的Javascript对象
- 为什么JavaScript在for循环为3时向所有4发出警报
- 另一个ajax调用中的Jquery ajax调用在for循环中没有按预期工作
- 循环结束/推送到数组之前在页面上呈现EJS
- 循环比赛位置算法
- jQuery循环在特定位置暂停
- 我的javascript for循环不起作用
- 循环浏览多个身体背景图像
- W3C循环样式的JavaScript
- HTML5的问题'for'循环,还有飞机