[英]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.