[英]Moving group of objects at the same time in canvas
我的问题是我不知道如何实现一组对象,在我的情况下,一组矩形同时移动。 好吧,我实现了轻松移动一个具有特定方向的矩形,您可以从我的代码中看到以下内容。 我也尝试添加一组矩形数组。 所以我的问题又是如何实现矩形组(例如3行3列,例如9行)以相同的方式在下面的代码中移动一个矩形? 因此,基本上组的最右侧和组的最左侧将碰到边界,而3X3中间的列将保持在3X3的两列之间移动。..任何帮助将不胜感激。 谢谢...
<html>
<head>
<title>Spaceman Invaders</title>
<script>
window.onload = function() {
var canvas = document.getElementById("screen");
context = canvas.getContext("2d");
context.fillStyle="black";
context.fillRect(0,0,canvas.width, canvas.height);
context.fillStyle = "red";
context.fillRect(30, 100, 20 , 20);
var posx = 27;
var posy = 100;
var go_right = true;
var go_down = false;
if (canvas.getContext) {
/* var array = [];
array.push(new Shape(20, 0, 50, 50, "red"));
array.push(new Shape(20, 60, 50, 50, "red"));
array.push(new Shape(20, 120, 50, 50, "red"));
array.push(new Shape(80, 0, 50, 50, "red"));
array.push(new Shape(80, 60, 50, 50, "red"));
array.push(new Shape(80, 120, 50, 50, "red"));
array.push(new Shape(140, 0, 50, 50, "red"));
array.push(new Shape(140, 60, 50, 50, "red"));
array.push(new Shape(140, 120, 50, 50, "red"));*/
setInterval( function() {
if (!go_down) {
if(posx < 250 && go_right) {
posx += 3;
} else if(posx < 30) {
go_right = true;
go_down = true;
} else if(!go_right) {
posx -= 3;
}else {
go_right = false;
go_down = true;
}
} else {
//if(posy <= 30)
posy += 5;
go_down = false;
}
context.fillStyle="black";
context.fillRect(0,0,canvas.width, canvas.height);
context.fillStyle = "red";
context.beginPath();
context.fillRect(posx, posy, 20 , 20);
context.fill();
}
, 20);
}
</script>
</head>
<body>
<canvas id="screen" width="300" height="500"/>
</body>
</html>
您将必须存储每个矩形的x,y位置。 您可以为此创建一个新类。 我给你举了一个例子:
var Alien = function(x, y) {
this.x = x;
this.y = y;
this.posx = 30 + x*30;
this.posy = 90 + y*30;
this.go_right = true;
this.go_down = false;
this.perrow = 3;
}
Alien.prototype.move = function() {
if (!this.go_down) {
if(this.posx + (this.perrow-1-this.x) * 30 < 250 && this.go_right) {
this.posx += 3;
} else if(this.posx < 30 + this.x*30) {
this.go_right = true;
this.go_down = true;
} else if(!this.go_right) {
this.posx -= 3;
} else {
this.go_right = false;
this.go_down = true;
}
} else {
//if(posy <= 30)
this.posy += 30;
this.go_down = false;
}
}
Alien.prototype.draw = function(context) {
if(this.x == 0) {
context.fillStyle = "red";
} else if(this.x == 1) {
context.fillStyle = "yellow";
} else {
context.fillStyle = "blue";
}
context.beginPath();
context.fillRect(this.posx, this.posy, 20 , 20);
context.fill();
}
然后,您可以更新位置并在intervall回调内部的循环中分别绘制每个对象。
编辑:现在,这些对象一下子全部向下移动。
您可以在这里进行测试: http : //jsfiddle.net/Z6F4d/3/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.