我正在创建的网页遇到更多麻烦。老实说,我不知道出了什么问题。我认为这可能与我的' 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>
答案 0 :(得分:1)
您的代码中有两个问题:
,0
airplaneArray.push(new plane(Math.floor(Math.random()*1000),100,1,1,imageArray[Math.floor(Math.random()*4)],100),0);
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));