HTML5的问题'for'循环,还有飞机

Problems with HTML5, 'for' loops, and airplanes

本文关键字:飞机 循环 HTML5 for 问题      更新时间:2023-09-26

我正在创建的网页有更多的麻烦。我真的不知道怎么了。我认为这可能与我的"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>

代码中的两个问题:

  1. airplaneArray.push(new plane(Math.floor(Math.random()*1000),100,1,1,imageArray[Math.floor(Math.random()*4)],100),0);中移除,0
  2. 将setTimeout更改为setTimeout('draw()',30);

我的一些小评论:

  1. <script>标签应放在</body>标签之前。
  2. 将所有的声明和数据准备移出draw()函数
  3. 应该改进你的算法来改变每个飞机的速度。示例:airplaneArray.push(new plane(Math.floor(Math.random()*1000),100,Math.floor(Math.random()*20)+1,1,imageArray[Math.floor(Math.random()*4)],100));