Javascript - 在div内移动多个图像,带边框控制

时间:2016-12-10 21:47:27

标签: javascript html image

小前提:我不想提出这个问题,因为我认为这是一个过于个人化和一般性的问题;但经过2天没有任何改善,我再也忍不住了。

基本上,我的项目是一个里面有多条鱼的水族馆 这一切都很好,唯一的问题是,简而言之:第一个鱼图像保留在div内(它甚至停止太快),第二个到达更远,第三个甚至更远,依此类推。 /> 相反的事情发生在上边缘:前进,最后一条鱼总是离边缘更远,我找不到原因。 我的范围是将所有鱼类保留在“acquario”div(具有黑色边框)内 附:使用sx和dx边距,它们没有问题。

var BORDER_LEFT_RIGHT = 7;
var BORDER_TOP_DOWN = 28;
var fishes = new Array();
var nextId = 0;
var heightMax;
var widthMax;
var n; //initial direction, see createFish()

init();
/* light blue fish (dory, to clarify)*/
createFish("https://s18.postimg.org/n8sqmtjkp/pesce1_sx.png", "https://s30.postimg.org/6w8xyqwep/pesce1_dx.png");
/* white and yellow fish */
createFish("https://s28.postimg.org/6aalv0pst/pesce2_sx.png", "https://s29.postimg.org/dxbi0vypz/pesce2_dx.png");
/* dark blue fish */
createFish("https://s24.postimg.org/sbgt8zn6t/pesce3_sx.png", "https://s29.postimg.org/v65opob7r/pesce3_dx.png");
/* white-blue-yellow fish */
createFish("https://s30.postimg.org/62lb9bfwx/pesce4_sx.png", "https://s28.postimg.org/kt5m4ea65/pesce4_dx.png");
/* orange fish */
createFish("https://s18.postimg.org/q5sq0saex/pesce5_sx.png", "https://s18.postimg.org/uqnwe2vex/pesce5_dx.png");
showFishes();

function init() {

  heightMax = document.getElementById("acquario").clientHeight - BORDER_TOP_DOWN;
  widthMax = document.getElementById("acquario").clientWidth - BORDER_LEFT_RIGHT;
  n = 1;
}

function createFish(src1, src2) {
  imgFishSX = new Image();
  imgFishDX = new Image();
  imgFishSX.src = src1;
  imgFishDX.src = src2;
  n *= -1;
  var fish = {
    id: nextId,
    /* default x position: random number between 1 and widthMax */
    x: Math.floor((Math.random() * widthMax - imgFishSX.width) + 1),
    /* default y position: random number between 1 and heightMax */
    y: Math.floor((Math.random() * heightMax - imgFishSX.height) + 1),
    xIncrease: n * getIncrease(),
    yIncrease: n * getIncrease(),
    imageSX: imgFishSX,
    imageDX: imgFishDX
  };
  addFishToArray((fish));
  nextId++;
}

function addFishToArray(fish) {
  fishes.push(fish);
}

function showFishes() {
  var node = document.getElementById("acquario");
  var stringToInner = "";
  var src;
  /* first, we make the string with all the img filled in */
  for (var i = 0; i < fishes.length; i++) {
    /* we have to check if the default increase direction was <-- or --> */
    fishes[i].xIncrease > 0 ? src = fishes[i].imageSX.src : src = fishes[i].imageDX.src;
    /* z-index --> overlap priority */
    stringToInner += "<img src =\"" + src +
      "\" id=\"" + fishes[i].id + "\" style= \"margin-left: " +
      fishes[i].x + "px;margin-top: " + fishes[i].y + "px;z-index: " +
      fishes[i].id + ";position: absolute;\">";
    stringToInner += "<br>";
  }

  /* then, we insert it */
  node.innerHTML = stringToInner;

  /* let's raise hell! */
  moveFishes();
}

function getIncrease() {
  return Math.floor((Math.random() * 5) + 1);
}

function moveFishes() {

  /* scroll the array: we need to check each fish one by one */
  for (var i = 0; i < fishes.length; i++) {
    moveFish(fishes[i]);
  }
  /* infinite loop */
  setTimeout(function() {
    moveFishes()
  }, 50);
}

function moveFish(fish) {
  /* with this node, I'll apply changes to my html document */
  node = document.getElementById(fish.id);
  /* we are inside, just move */
  if (fish.x > 0 && fish.x < widthMax - node.width && fish.y > 0 && fish.y < heightMax - node.height) {
    node.style.marginLeft = fish.x + "px";
    node.style.marginTop = fish.y + "px";
    fish.x += fish.xIncrease;
    fish.y += fish.yIncrease;
    /* too --> , we need to get <-- */
  } else if (fish.x >= widthMax - node.width) {
    node.src = fish.imageDX.src;
    fish.xIncrease = -getIncrease();
    fish.x += fish.xIncrease;
    /* too <-- , we need to get --> */
  } else if (fish.x <= 0) {
    node.src = fish.imageSX.src;
    fish.xIncrease = 5;
    fish.x += getIncrease();
    /* too up, we need to get down */
  } else if (fish.y >= heightMax - node.height) {
    fish.yIncrease = -getIncrease();
    fish.y += fish.yIncrease;
    /* too down, we need to get up */
  } else if (fish.y <= 0) {
    fish.yIncrease = getIncrease();
    fish.y += fish.yIncrease;
  }
}
* {
  box-sizing: border-box;
}
.row::after {
  content: "";
  clear: both;
  display: block;
}
html {
  background: url("https://s24.postimg.org/rakxoa7sl/sfondo.jpg") no-repeat center center fixed;
  -webkibact-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
html,
body {
  height: 100%;
  margin: 0;
}
#main {
  margin: 0;
  height: 100%;
}
#acquario {
  border-bottom: 28px solid black;
  border-top: 28px solid black;
  border-right: 7px solid black;
  border-left: 7px solid black;
  height: 100%;
}
<body>
  <div id="main">
    <div id="acquario">
    </div>
  </div>
</body>

2 个答案:

答案 0 :(得分:1)

你想要将鱼类挡在墙上还是藏在墙下?为什么你使用margin-left和margin-top而不是top和left属性?它使水族馆滚动。现在好吗?

var BORDER_LEFT_RIGHT = 7;
var BORDER_TOP_DOWN = 28;
var fishes = new Array();
var nextId = 0;
var heightMax;
var widthMax;
var n; //initial direction, see createFish()

init();
/* light blue fish (dory, to clarify)*/
createFish("https://s18.postimg.org/n8sqmtjkp/pesce1_sx.png", "https://s30.postimg.org/6w8xyqwep/pesce1_dx.png");
/* white and yellow fish */
createFish("https://s28.postimg.org/6aalv0pst/pesce2_sx.png", "https://s29.postimg.org/dxbi0vypz/pesce2_dx.png");
/* dark blue fish */
createFish("https://s24.postimg.org/sbgt8zn6t/pesce3_sx.png", "https://s29.postimg.org/v65opob7r/pesce3_dx.png");
/* white-blue-yellow fish */
createFish("https://s30.postimg.org/62lb9bfwx/pesce4_sx.png", "https://s28.postimg.org/kt5m4ea65/pesce4_dx.png");
/* orange fish */
createFish("https://s18.postimg.org/q5sq0saex/pesce5_sx.png", "https://s18.postimg.org/uqnwe2vex/pesce5_dx.png");
showFishes();

function init() {

  heightMax = document.getElementById("acquario").clientHeight + BORDER_TOP_DOWN;
  widthMax = document.getElementById("acquario").clientWidth + BORDER_LEFT_RIGHT;
  n = 1;
}

function createFish(src1, src2) {
  imgFishSX = new Image();
  imgFishDX = new Image();
  imgFishSX.src = src1;
  imgFishDX.src = src2;
  n *= -1;
  var fish = {
    id: nextId,
    /* default x position: random number between 1 and widthMax */
    x: Math.floor((Math.random() * (widthMax - BORDER_LEFT_RIGHT - imgFishSX.width)) + BORDER_LEFT_RIGHT),
    /* default y position: random number between 1 and heightMax */
    y: Math.floor((Math.random() * (heightMax - BORDER_TOP_DOWN - imgFishSX.height)) + BORDER_TOP_DOWN),
    xIncrease: n * getIncrease(),
    yIncrease: n * getIncrease(),
    imageSX: imgFishSX,
    imageDX: imgFishDX
  };
  addFishToArray((fish));
  nextId++;
}

function addFishToArray(fish) {
  fishes.push(fish);
}

function showFishes() {
  var node = document.getElementById("acquario");
  var stringToInner = "";
  var src;
  /* first, we make the string with all the img filled in */
  for (var i = 0; i < fishes.length; i++) {
    /* we have to check if the default increase direction was <-- or --> */
    fishes[i].xIncrease > 0 ? src = fishes[i].imageSX.src : src = fishes[i].imageDX.src;
    /* z-index --> overlap priority */
    stringToInner += "<img src =\"" + src +
      "\" id=\"" + fishes[i].id + "\" style= \"left: " +
      fishes[i].x + "px;top: " + fishes[i].y + "px;z-index: " +
      fishes[i].id + ";position: absolute;\">";
    stringToInner += "<br>";
  }

  /* then, we insert it */
  node.innerHTML = stringToInner;


  /* let's raise hell! */
  moveFishes();
}

function getIncrease() {
  return Math.floor((Math.random() * 5) + 1);
}

function moveFishes() {

  /* scroll the array: we need to check each fish one by one */
  for (var i = 0; i < fishes.length; i++) {
    moveFish(fishes[i]);
  }
  /* infinite loop */
  setTimeout(function() {
    moveFishes()
  }, 50);
}

function moveFish(fish) {
  /* with this node, I'll apply changes to my html document */
  node = document.getElementById(fish.id);
  /* we are inside, just move */
  if (fish.x > BORDER_LEFT_RIGHT && fish.x < widthMax - node.width && fish.y > BORDER_TOP_DOWN && fish.y < heightMax - node.height) {
    node.style.left = fish.x + "px";
    node.style.top = fish.y + "px";
    fish.x += fish.xIncrease;
    fish.y += fish.yIncrease;
    /* too --> , we need to get <-- */
  } else if (fish.x >= widthMax - node.width) {
    node.src = fish.imageDX.src;
    fish.xIncrease = -getIncrease();
    fish.x += fish.xIncrease;
    /* too <-- , we need to get --> */
  } else if (fish.x <= BORDER_LEFT_RIGHT) {
    node.src = fish.imageSX.src;
    fish.xIncrease = 5;
    fish.x += getIncrease();
    /* too up, we need to get down */
  } else if (fish.y >= heightMax - node.height) {
    fish.yIncrease = -getIncrease();
    fish.y += fish.yIncrease;
    /* too down, we need to get up */
  } else if (fish.y <= BORDER_TOP_DOWN) {
    fish.yIncrease = getIncrease();
    fish.y += fish.yIncrease;
  }
}
* {
  box-sizing: border-box;
}
.row::after {
  content: "";
  clear: both;
  display: block;
}
html {
  background: url("https://s24.postimg.org/rakxoa7sl/sfondo.jpg") no-repeat center center fixed;
  -webkibact-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
html,
body {
  height: 100%;
  margin: 0;
}
#main {
  margin: 0;
  height: 100%;
}
#acquario {
  border-bottom: 28px solid black;
  border-top: 28px solid black;
  border-right: 7px solid black;
  border-left: 7px solid black;
  height: 100%;
}
<body>
  <div id="main">
    <div id="acquario">
    </div>
  </div>
</body>

答案 1 :(得分:0)

我知道Pawel已经解决了你的问题,但是我说我会提供一个画布版本,所以这里是

jsFiddle:cppreference

HTML:

<canvas id="myCanvas"></canvas>

CSS:

html,
body {
  width: 100%;
  height: 100%;
  margin: 0px;
  overflow: hidden;
}

Javascript:

var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext("2d");
var backgroundImage = new Image();
canvas.width = document.body.clientWidth; //document.width is obsolete
canvas.height = document.body.clientHeight; //document.height is obsolete

// Fish
function FishObject(xSet, ySet, xSpeed, ySpeed, spriteUrlRight, spriteUrlLeft) {
  this.XPos = xSet;
  this.YPos = ySet;
  this.XDefaultSpeed = xSpeed;
  this.YDefaultSpeed = ySpeed;
  this.xSpeed = this.XDefaultSpeed;
  this.ySpeed = this.YDefaultSpeed;
  this.RightSprite = new Image();
  this.RightSprite.src = spriteUrlRight;
  this.LeftSprite = new Image();
  this.LeftSprite.src = spriteUrlLeft;
}

FishObject.prototype.Draw = function(ctx) {
  if (this.xSpeed > 0) {
    ctx.drawImage(this.RightSprite, this.XPos, this.YPos);
  } else {
    ctx.drawImage(this.LeftSprite, this.XPos, this.YPos);
  }
}

FishObject.prototype.Update = function(ctx) {
  this.XPos += this.xSpeed;
  this.YPos += this.ySpeed;

  if (this.XPos <= 0) {
    this.xSpeed = this.XDefaultSpeed;
  } else if ((this.XPos + this.RightSprite.width) >= canvas.width) {
    this.xSpeed = -this.XDefaultSpeed;
  }

  if (this.YPos <= 0) {
    this.ySpeed = this.YDefaultSpeed;
  } else if ((this.YPos + this.RightSprite.height) >= canvas.height) {
    this.ySpeed = -this.YDefaultSpeed;
  }
}

backgroundImage.src = 'https://s24.postimg.org/rakxoa7sl/sfondo.jpg';

var Fishs = [];
Fishs.push(new FishObject(0, 0, 1, 1, "https://s18.postimg.org/n8sqmtjkp/pesce1_sx.png",
  "https://s30.postimg.org/6w8xyqwep/pesce1_dx.png"));
Fishs.push(new FishObject(0, 0, 2, 1.2, "https://s28.postimg.org/6aalv0pst/pesce2_sx.png",
  "https://s29.postimg.org/dxbi0vypz/pesce2_dx.png"));
Fishs.push(new FishObject(0, 0, 1.7, 2.8, "https://s24.postimg.org/sbgt8zn6t/pesce3_sx.png",
  "https://s29.postimg.org/v65opob7r/pesce3_dx.png"));
Fishs.push(new FishObject(0, 0, 0.2, 0.5, "https://s30.postimg.org/62lb9bfwx/pesce4_sx.png",
  "https://s28.postimg.org/kt5m4ea65/pesce4_dx.png"));
Fishs.push(new FishObject(0, 0, 0.7, 0.1, "https://s18.postimg.org/q5sq0saex/pesce5_sx.png",
  "https://s18.postimg.org/uqnwe2vex/pesce5_dx.png"));

setInterval(function() {
  ctx.fillStyle = "#000";
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  ctx.drawImage(backgroundImage, 0, 0);

  for (var i = 0; i < Fishs.length; i++) {
    var fishObject = Fishs[i];
    fishObject.Draw(ctx);
    fishObject.Update(ctx);
  }

}, (1000 / 60)); // 60 FPS (frames per second)