JavaScript动画,IMG在屏幕上移动,每次触摸屏幕限制时,他们都会转向方向

javascript animation, a img move in the screen and every time when they touch the screen limit, they turn direction

本文关键字:屏幕 他们 方向 触摸 IMG 动画 移动 JavaScript 触摸屏      更新时间:2023-09-26

嘿伙计们,我试图制作一个代码来在窗口中移动图像,img 将一直向同一方向移动,直到达到屏幕限制,并且它们将更改直接以继续移动,我制作的代码如下:

var flySpeed = 5;
var maxWidth = window.innerWidth;
var maxHeight = window.innerHeight;
var xPosition = 0;
var yPosition =0;
var xDirection = "right";
var yDirection = "down";

function movingBug()
{
    var bug = document.getElementById("bugImg");
    bug.style.left = xPosition + "px";
    bug.style.top = yPosition + "px";
    bug.style.position="absolute";
if (xDirection =="right")
    ++xPosition;
else if (xDirection =="left")
    ++xPosition;
if(yDirection =="down")
    ++yPosition;
else if (yDirection =="up")
    --yPosition;
 if(xPosition == screen.availWidth - 100)
 {
    xDirection ="left";
    yDirection = "down";
 }
if(xPosition == screen.availWidth - 10)
{
    xDirection = "right";
    yDirection = "up";
}
if(yPosition == screen.availHeight - 100)
{
    xDirection = "left";
    yDirection = "down";
}
if(yPosition == screen.availHeight - 10)
{
xDirection = "right";
yDirection = "up";
}

}

网页部分:

<body onload="setInterval('movingBug()',2);">
     <div id="bugImg"><img src = "Mosquito1.jpg" id ="bug1" width=100px; height=100px;></div>
</body>

现在,我想我需要使用数学随机才能让它随机移动,我应该在哪里添加它?

你错误地使用了 ++ 而不是 --

if (xDirection =="right")
    ++xPosition;
else if (xDirection =="left")
    --xPosition;//here

此外,您还缺少:

if(yPosition == screen.availHeight - 10)
   {
    xDirection = "right";
    yDirection = "up";
   }