I'm trying to move an image within a set radius of 100 pixels. I'm having some trouble getting it to work.
I'm using setInterval to make it repeatedly move and random to set where it moves.
Full JS code:
function start () {
const imgH = 111;
const imgW = 112;
const scrnH = screen.availHeight;
const scrnW = screen.availWidth;
var objX = scrnW/2 - imgW/2;
var objY = scrnH/2 - imgH/2;
document.getElementById("monka").style.top = objY + "px";
document.getElementById("monka").style.left = objX + "px";
var x = document.getElementById("monka").style.left;
var y = document.getElementById("monka").style.top;
var deltaX = 0;
var deltaY = 0;
function move () {
if ((Math.sqrt(x ** 2 + y ** 2) >= 100) || (deltaX == 0 && deltaY == 0)) {
deltaX = -1 * deltaX;
deltaY = -1 * deltaY;
} else {
x += deltaX;
y += deltaY;
document.getElementById("monka").style.left = x;
document.getElementById("monka").style.top = y;
deltaX = Math.ceil(Math.random() * 50) - 25;
deltaY = Math.ceil(Math.random() * 50) - 25;
}
}
setInterval("move()", 100);
}
Full HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Random Movement</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="script.js"></script>
</head>
<body onLoad="start();">
<img src="monkaW.png" id="monka" style="">
</body>
</html>
const monka = document.getElementById("monka")then you can usemonka.style.left. 3. Not a big fan of thebody onLoad=syntax, I suggest you move your script to the end of your body, that way you don't need to wrap it all in a function. 4. setInterval should be a callback, in ES6:setInterval(() => {move()}, 100)