当图像到达屏幕边缘时更改图像源

时间:2020-12-22 02:28:20

标签: javascript html css

我这里有一个 DVD 屏幕保护程序的代码。

我想让每次图像到达边缘时,它都会更改为不同的图像 src。我似乎无法弄清楚如何更改它。

我尝试过使用这种技术:

var img = document.getElementById("myImage");
img.src = 'img/new-image.jpg';

但我认为我实施它是错误的,因为它似乎不起作用。非常感谢任何帮助 - 下面的片段。

const section = document.querySelector("section");
const logo = document.querySelector(".logo");
const FPS = 60;
section.style.height = window.innerHeight + "px";
section.style.width = window.innerWidth + "px";

// Logo moving velocity Variables
let xPosition = 10;
let yPosition = 10;
let xSpeed = 4;
let ySpeed = 4;
function update() {
  logo.style.left = xPosition + "px";
  logo.style.top = yPosition + "px";
}

setInterval(() => {
  if (xPosition + logo.clientWidth >= window.innerWidth || xPosition <= 0) {
    xSpeed = -xSpeed;
  }
  if (yPosition + logo.clientHeight >= window.innerHeight || yPosition <= 0) {
    ySpeed = -ySpeed;
  }

  xPosition += xSpeed;
  yPosition += ySpeed;
  update();
}, 1000 / FPS);

window.addEventListener("resize", () => {
  xPosition = 10;
  yPosition = 10;

  section.style.height = window.innerHeight + "px";
  section.style.width = window.innerWidth + "px";
});
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
body {
  overflow: hidden;
}
section {
  position: relative;
}
svg {
  position: absolute;
  width: 200px;
  fill: rgb(0, 81, 255);
}
@media (max-width: 768px) {
  svg {
    width: 150px;
  }
}
<section>
  <svg class="logo"  xmlns="http://www.w3.org/2000/svg">
      <image id="imageID" href="https://i.imgur.com/gcrU9si.jpg" height="160" width="200"/>
  </svg>
</section>

1 个答案:

答案 0 :(得分:1)

你可以试试这个 (https://jsfiddle.net/56emzjws/)

*
相关问题