Looping code with a delay - javascript

I am trying to create a simple drag race animation. The car image moves across the page upon the click of a button until each reaches a certain position. The code below works with individual clicks moving the car a random distance each click, but I want one click to repeat the movement in a loop. I have tried putting it in a while loop referencing the value of x, but it doesn't work. Any ideas.
<html>
<head>
<meta charset="utf-8">
<title>Race Car</title>
</head>
<body>
<input type="button" id="move" value="race time" onClick="race()" />
<div id="car" style="position: absolute; top: 150px"><img src="car.png"></div>
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>
<script>
//Get car position coordinates
x = $("#car").offset().left;
y = $("#car").offset().top;
//Move car across screen by resetting car position coordinates
var race = function() {
var delay = 1000;
setTimeout(function() {
$("#car").css({
left: x += Math.floor(Math.random() * 50),
top: y
});
x = $("#car").offset().left;
}, delay);
};
</script>
</body>
</html>

You're looking for setInterval.
setTimeout runs your function once after x milliseconds.
setInterval runs your function every x milliseconds.
Be sure to store your interval in a variable you can access (var timer = setInterval(fn, ms)) and then clear it when you want to stop the interval (clearInterval(timer)).

Why are you using variables instead of standard functions? Anyway, you can call your function recursively from within the setTimeout function until a condition is met. Try this:
<html>
<head>
<meta charset="utf-8">
<title>Race Car</title>
</head>
<body>
<input type="button" id="move" value="race time" onClick="race()" />
<div id="car" style="position: absolute; top: 150px"><img src="car.png"></div>
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>
<script>
//Get car position coordinates
x = $("#car").offset().left;
y = $("#car").offset().top;
//Move car across screen by resetting car position coordinates
function race() {
var delay = 1000;
setTimeout(function() {
$("#car").css({
left: x += Math.floor(Math.random() * 50),
top: y
});
if (x < 200) //Specify where you want the movement to end.
race();
}, delay);
}
</script>
</body>
</html>

You should use recursive setTimeout() not setInterval().
See why here --> https://develoger.com/settimeout-vs-setinterval-cff85142555b
This is how I like to approach this problem, with the function bellow you can pass number of iterations, time in between and actually callback.
How many times? (you can set infinity)
For how much to delay (in seconds)
And to do WHAT?
See working example here --> https://jsfiddle.net/nmitic/bbr6y2a4/
const repeat = (numberOfIterations, timeBetweenItereation, stuffToRepeat) => {
let iterationCounter = 0;
const repeater = () => {
setTimeout( () => {
stuffToRepeat();
iterationCounter++;
if (iterationCounter >= numberOfIterations && numberOfIterations
!== Infinity) {
return;
};
if (iterationCounter >= numberOfIterations) {
return;
};
repeater();
}, 1000 * timeBetweenItereation);
};
repeater();
};

This will clear interval whenever you click the button and the race starts from the begining.
Also no ned to set the top at every call, just left is enough.
Happy racing!!!
x = $("#car").offset().left;
y = $("#car").offset().top;
//Move car across screen by resetting car position coordinates
var interval;
var race = function() {
clearInterval(interval);
var delay = 100, x=0;
interval = setInterval(function() {
$("#car").css({
left: x += Math.floor(Math.random() * 50),
});
x = $("#car").offset().left;
}, delay);
};
<input type="button" id="move" value="race time" onClick="race()" />
<div id="car" style="position: absolute; top: 150px"><img src="car.jpg"></div>

Related

How to change the time in setInterval with an user input?

I want to know a way to change the setInterval time so my image would move across the screen at that pace. Example if i put in 500 milliseconds it would change the time interval from 250 to 500 when i click a button. Here is what I came up with so far.
var x;
var y;
var timing = 1000;
function window_onLoad() {
x = 0;
y = 100;
window.setInterval("MoveBall()", timing);
picBall.style.top = y + "px";
}
function MoveBall() {
x = x + 5;
if (x < document.body.clientWidth - 91) {
picBall.style.left = x + "px";
}
}
function btnReset_OnClick() {
x = 0;
}
function btnSpeed_OnClick() {
timing = parseInt(txtSpeed.value);
}
window_onLoad()
<img id="picBall" src="Face.jpg" style="position: absolute;"/>
<input id="btnReset" type="button" value="Reset position"
onclick="btnReset_OnClick()"/>
<input id="txtSpeed" type="text"/>
<input id="btnSpeed" type="button" value="Change Speed"
oclick="btnSpeed_onClick()"/>
I suggest not to mix moving speed with framerate (your setInterval speed). You can have a fixed framerate and variable speed. E.g.
var speed = 1, timer, x,y;
function window_onLoad() {
x = 0;
y = 100;
window.setInterval("MoveBall()", 100); // 10 frames per second
picBall.style.top = y + "px";
}
function MoveBall() {
x = x + speed;
if (x < document.body.clientWidth - 91) {
picBall.style.left = x + "px";
}
}
function btnReset_OnClick() {
x = 0;
}
function btnSpeed_OnClick() {
/*
speed = 200 will move tbe ball by 20px per sec
speed = 100 will move the ball by 10px per sec
speed = 50 will move the ball by 5px per sec
*/
speed = parseInt(txtSpeed.value)/100;
}
Your main issue is that you need to clear the previous interval and create a new one. However, I'd recommend moving your code that creates the interval into another function like this...
function window_onLoad() {
x = 0;
y = 100;
createInterval(timing);
picBall.style.top = y + "px";
}
var intervalId = 0;
// this will destroy any existing interval and create a new one
function createInterval(interval) {
clearInterval(intervalId);
intervalId = setInterval(MoveBall, interval);
}
function btnSpeed_OnClick() {
timing = parseInt(txtSpeed.value);
createInterval(timing);
}
You have to save a reference to interval and then, every time you want to change the speed you have to clear the previous interval with clearInterval and then apply a new interval, like this:
var x;
var y;
var timing = 1000;
var interval;
function window_onLoad() {
x = 0;
y = 100;
applyInterval();
picBall.style.top = y + "px";
}
function applyInterval() {
if (interval) {
console.log('Clearing previous interval');
clearInterval(interval);
}
console.log('Applying new interval');
interval = window.setInterval("MoveBall()", timing);
}
function MoveBall() {
x = x + 5;
if (x < document.body.clientWidth - 91) {
picBall.style.left = x + "px";
}
}
function btnReset_OnClick() {
x = 0;
}
function btnSpeed_OnClick() {
timing = parseInt(txtSpeed.value);
applyInterval();
}
window_onLoad()
<img id="picBall" src="https://i.stack.imgur.com/vnucx.png?s=64&g=1" style="position: absolute;" width="25" height="25"/>
<input id="btnReset" type="button" value="Reset position"
onclick="btnReset_OnClick()"/>
<input id="txtSpeed" type="text"/>
<input id="btnSpeed" type="button" value="Change Speed"
onclick="btnSpeed_OnClick()"/>

Moving Div Box just using pure javascript at certain time

I have saw the problem
Moving Div Box using javascript
and the top upvote answer is good .
But if I want to get the feacture like CSS3 does ,how can I do?
.cuble{
height: 100px;
width: 100px;
background-color: blue;
transition: all 3s ease-in-out;
}
.cuble:hover{
transform: translateX(500px);
}
<!Doctype html>
<html>
<body>
<div class="cuble">
</div>
</body>
I don't need ease-in-out effect .I just want hover the div once and even if I mouseout the div ,the div will also moving from left to right until the setting time. But the Moving Div Box using javascript don't meet the requirement.
I try to use Promise to achieve the goal ,here is my Javascript code .(anyway,maybe I just want to learn deep about javascript async performance)
var cuble = document.querySelector('.cuble');
cuble.onmouseover = function(e) {
for (var i = 0; i < 100; i++) {
var pixels = 5 * i + "px";
delay(100)
.then(() => cuble.style.marginLeft = pixels)
}
}
function delay(t) {
return new Promise(function(resolve) {
setTimeout(resolve, t)
});
};
How can I fix my Javascript code and meet the requirement?
The issue is you're creating one hundred promises each with a 100ms delay almost instantly, so they all firing almost instantly.
One way to remedy the issue is increase the delay for each subsequent promise. And you also have to pass the corresponding pixels for each resolve. Something like:
var cuble = document.querySelector('.cuble');
cuble.onmouseover = function(e) {
for (var i = 0; i < 100; i++) {
var pixels = 5 * i + "px";
delay(i * 20, pixels)
.then((p) => cuble.style.marginLeft = p)
}
}
function delay(t, pixels) {
return new Promise(function(resolve) {
setTimeout(() => resolve(pixels), t)
});
};
DEMO
An example with no promises and just one function being created and called, instead of creating new function for every step:
var cuble = document.querySelector('.cuble');
cuble.onmouseover = function() {
var left = 0,
ival = setInterval(move, 5);
function move() {
if (left === 500) clearInterval(ival);
cuble.style.marginLeft = left++ + 'px';
}
}
DEMO

Why does my setInterval function not work second time? (JavaScript)

I made a div and I want to make it animate in a specific direction every 1 second. In the code that I have provided there's a function called resetPosition() don't worry about that, it's from my other js file that I linked in the head section(That works perfectly). I just want to know why setInterval() doesn't work correctly?
Here's my code:-
<!DOCTYPE html>
<html>
<head>
<title>Animtion</title>
<link rel="icon" href="http://3.bp.blogspot.com/-xxHZQduhqlw/T-cCSTAyLQI/AAAAAAAAAMw/o48rpWUeg2E/s1600/html-logo.jpg" type="image/jpg">
<script src="easyJs.js"></script>
<style type="text/css">
div{height:100px; width:100px; background:cyan;}
</style>
</head>
<body onload="">
<div id="demo"></div>
</body>
<script type="text/javascript">
setInterval(function(){var x = new element('demo');
x.resetPosition('absolute', '100px', '10px');}, 1000);
</script>
</html>
Here's easyJs:-
function element(elementId){
this.myElement = document.getElementById(elementId);
this.resetColor = changeColor;
this.resetSize = changeSize;
this.resetBackground = changeBackground;
this.resetPosition = changePosition;
this.resetBorder = changeBorder;
this.resetFontFamily = changeFont;
this.resetFontSize = changeFontSize;
this.resetFontStyle = changeFontStyle;
this.resetZindex = changeZindex;
this.resetClass = changeClass;
this.resetTitle = changeTitle;
this.resetMarginTop = changeMarginTop;
this.resetMarginLeft = changeMarginLeft;
this.resetSource = changeSource;
this.resetInnerHTML = changeInnerHTML;
this.resetHref = changeHref;
this.resetTextDecoration = changeTextDecoration;
this.resetFontWeight = changeFontWeight;
this.resetCursor = changeCursor;
this.resetPadding = changePadding;
this.getValue = getTheValue;
this.getName = getTheName;
this.getHeight = getTheHeight;
}
function changeColor(color){
this.myElement.style.color = color;
}
function changeSize(height, width){
this.myElement.style.height = height;
this.myElement.style.width = width;
}
function changeBackground(color){
this.myElement.style.background = color;
}
function changePosition(pos, x, y){
this.myElement.style.position = pos;
this.myElement.style.left = x;
this.myElement.style.top = y;
}
function changeBorder(border){
this.myElement.style.border = border;
}
function changeFont(fontName){
this.myElement.style.fontFamily = fontName;
}
function changeFontSize(size){
this.myElement.style.fontSize = size;
}
function changeZindex(indexNo){
this.myElement.style.zIndex = indexNo;
}
function changeClass(newClass){
this.myElement.className = newClass;
}
function changeTitle(newTitle){
this.myElement.title = newTitle;
}
function changeMarginTop(top){
this.myElement.style.marginTop = top;
}
function changeMarginLeft(left){
this.myElement.style.marginLeft = left;
}
function changeSource(newSource){
this.myElement.src = newSource;
}
function changeHref(newHref){
this.myElement.href = newHref;
}
function changeInnerHTML(newHTML){
this.myElement.innerHTML = newHTML;
}
function changeTextDecoration(decoration){
this.myElement.style.textDecoration = decoration;
}
function changeFontWeight(weight){
this.myElement.style.fontWeight = weight;
}
function changeFontStyle(style){
this.myElement.style.fontStyle = style;
}
function changeCursor(cursor){
this.myElement.style.cursor = cursor;
}
function changePadding(padding){
this.myElement.style.padding = padding;
}
function getTheValue(){
var theValue = this.myElement.value;
return theValue;
}
function getTheName(){
var theName = this.myElement.name;
return theName;
}
function getTheHeight(){
var theHeight = this.myElement.offsetHeight;
return theHeight;
}
This might help you see what and how. (Scroll down to bottom of code):
Fiddle
// Create a new EasyJS object
var el = new element('demo');
// x and y position of element
var x = 0, y = 0;
// Interval routine
setInterval(function(){
x = x + 1; // Increment x by 1
y = y + 1; // Increment y by 1
// Move element to position xy
el.resetPosition('absolute', x + 'px', y + 'px');
// Add text inside element showing position.
el.resetInnerHTML(x + 'x' + y);
// Run five times every second
}, 1000 / 5);
Explanation of original code:
setInterval(function() {
// Here you re-declare the "x" object for each iteration.
var x = new element('demo');
// Here you move the div with id "demo" to position 100x10
x.resetPosition('absolute', '100px', '10px');
// Once every second
}, 1000);
The HTML div element demo initially has no positioning styling (CSS). As such it is rendered in the default position according to the browser defaults.
In first iteration you change the style option position to absolute. That means you can move it anywhere. Secondly you move it to offset 100x10.
On the second and every iteration after that the element has position set to absolute, and it reside at 100x10. Then you say it should be moved to 100x10 – as in same place as it is.
If you do not change either x or y position (left / top), it will stay at 100x10, no mather how many times you run the loop. Run it 100 times a second for a year and it will still be at 100x10 ;-)
Think about it. Everytime the interval runs, it creates a new instance of element "demo".
This demo variable has all the default values your elements object sets it to (if any), and runs the same function each time. That's why it only moves once.
Hoist your element higher and you won't be re-declaring each interval.
<script type="text/javascript">
var x = new element('demo');
setInterval(function(){
x.resetPosition('absolute', '100px', '10px');}, 1000);
</script>
The problem isn't in the setInterval, because a copypasta'd fiddle of the same expression worked properly, so it's probably either an issue with resetPosition or maybe easyJS, though I doubt the latter.
Also, it's unclear whether demo appears on-page, as it's not added anywhere visibly.
EDIT:
If demo is appended somewhere behind the scenes, it's still piling a new demo on that spot every second

Making a 'div' go in a circle

I am working on a bit of code to have a dot circle around your cursor on a webpage, but I am having trouble getting the 'div' to follow the path I want; in fact, the object is not moving at all and I cannot figure out why my code does not work. Here is the code that is causing me trouble from what I've narrowed down:
<!DOCTYPE HTML>
<head>
<title>TEST SPACE</title>
<script src="jquery-1.10.2.min.js"></script>
</head>
<body>
<div id="test"></div>
<style>
#test {
background-color: black;
height: 10px;
width: 10px;
border-radius: 100%;
position: absolute;
top: 50%;
left: 50%;
}
</style>
<script>
const omega = Math.PI / 2000;
function dotRotation() {
var time = 0;
var x = 20*(Math.sin(omega*time));
var y = 20*(Math.cos(omega*time));
document.getElementById("test").style.marginLeft = x;
document.getElementById("test").style.marginTop = y;
time += 25;
};
$(document).ready(function() {
setInterval('dotRotation()',25);
});
</script>
</body>
JSFiddle
Two things are wrong
You need to move your time variable outside of the function
You need to give a unit to the value you pass to the margins so add +'px' after the variables .marginTop = y + 'px';
So altogether
const omega = Math.PI / 2000;
var time = 0;
function dotRotation() {
var x = 20*(Math.sin(omega*time));
var y = 20*(Math.cos(omega*time));
var style = document.getElementById("test").style;
style.marginLeft = x +'px';
style.marginTop = y +'px';
time += 25;
};
Demo at http://jsfiddle.net/mWC63/
Also you can cache references to the dom to avoid the searching
Your fiddle is set to run onload, it should be set up to run in the head. [drop down on left under jQuery selection.]
time is declared inside of the function so it is reset back to zero every single time it is called. Move it outside of dotRotation
var time = 0;
function dotRotation() {
var x = 20*(Math.sin(omega*time));
var y = 20*(Math.cos(omega*time));
$("#test").css({"marginLeft" : x + "px", "marginTop" : y + "px"});
time += 25;
};
$(function() {
setInterval(dotRotation,25);
});

coding 2D game physics in javascript, not-flat ground and rotation

I have a small project in my webprogramming course where I am supposed to make a small game in javascript. This is the game: two cannons are fixed on
opposing ends of the game space. The cannons take turns shooting at each other, and the player tilts the cannon to some degree and chooses a force to shoot the cannonball with. There's a bunch of other stuff I'm thinking of that will be added if there's time.
I found a nice site, http://www.rodedev.com/tutorials/gamephysics/, to get me going with 2d physics and I've made some tests, see the code below. I do however have two big problems:
Non-flat floor/ground.
Rotation!
Right now the script is only checking for the style.top value of the floorDiv, so the box will always "land" on this row of pixels. If I want to have
variable-height terrain, this won't suffice. Any ideas from you guys on how this could be accomplished? Is there anyway to check the color at a specific pixel? If so I could check for non-sky or ground colored pixels and make this the landing critera.
I need to rotate the cannon so players can adjust their aim! I'm thinking I'll make two different cannon objects, the cannon "base" and the cannon barrel. Then I could just rotate the cannon barrel when the player presses a key. Unfortunately rotation seems to be hard in webprogramming. I found this jquery plugin, at http://code.google.com/p/jquery-rotate/, but I'm not getting it to work quite as I would like. Even though I've made sure the cannonball is centered in the picture there is also some translation, not just rotation.
I suppose this might be because the picture doesn't rotate about it's center? See the rotation test code below (you'll have to download
the rotation plugin if you want to try the code).
I suppose I could just make a picture for each angle but that seems kind of wasteful
since there's no actual visual change to the cannon otherwise.
Also, if I want to animate several objects at the same time, do you think I should just change all the objects in the same gameloop function?
Any ideas on this?
The following is the code for the physics-testing
CSS-file
#moveDiv {
position:absolute;
width:100px;
height:100px;
background-color:#000;
}
#floorDiv {
position:absolute;
width:800px;
height:1px;
background-color:#2E2;
}
table {
text-align:right;
}
table input {
width:35px;
}
HTML-file
<script type="text/javascript">
//global vars
var gravity = 0.5;
var friction = 0.5;
var moving = false;
var moveDiv;
var floorDiv;
var yPos;
var xPos;
var floorPos;
var velocity_y = 0;
var velocity_x = 0;
</script>
</head>
<body onload="initialize();">
<input type="button" value="fall" onclick="fall();"></button>
<input type="button" value="Push" onclick="push();"></button>
<input type="button" value="reset" onclick="reset();"></button>
<table>
<tr>
<td>Angle: <input type="text" value="45" id="angle" /></td>
<td>Speed: <input type="text" value="10" id="speed"/></td>
</tr>
<tr>
<td>Gravity: <input type="text" value="0.5" id="gravity" /></td>
<td>Friction: <input type="text" value="0.5" id="friction" /></td>
</table>
<div id="moveDiv"></div>
<div id="floorDiv"></div>
</body>
</html>
js-file
function initialize() {
moveDiv = document.getElementById('moveDiv');
floorDiv = document.getElementById('floorDiv');
moveDiv.style.left=400;
moveDiv.style.top=50;
floorDiv.style.left=200;
floorDiv.style.top=400;
}//end initialize
function fall()
{
moving=true;
var angle = 275;
var rad = angle / (Math.pi * 2);
var scale_x = Math.cos(rad);
var scale_y = Math.sin(rad);
var moveDivSpeed = 0;
gameLoop();
}//end fall
function push()
{
moving=true;
var angle = document.getElementById('angle').value;
var rad = angle / (Math.PI * 2);
var scale_x = Math.cos(rad);
var scale_y = Math.sin(rad);
var moveDivSpeed = document.getElementById('speed').value;
friction = document.getElementById('friction').value;
gravity = document.getElementById('gravity').value;
velocity_x = moveDivSpeed*scale_x;
console.log("original velocity_x is " + velocity_x);
velocity_y = moveDivSpeed*scale_y;
gameLoop();
}
function gameLoop () {
//console.log("gameLoop start");
var len = moveDiv.style.top.length;
var presentTop = parseInt(moveDiv.style.top.substr(0, len-2));
var lenX = moveDiv.style.left.length;
var presentLeft = parseInt(moveDiv.style.left.substr(0, lenX-2));
var len2 = floorDiv.style.top.length;
var floorTop = parseInt(floorDiv.style.top.substr(0, len2-2));
if (moving == true)
{
velocity_y -= gravity;
if ((presentTop+100) - velocity_y < floorTop)
{ //if moveDiv hasn't hit the floor yet...
moveDiv.style.top = presentTop - velocity_y;
moveDiv.style.left = presentLeft + velocity_x;
}
else if (presentTop + 100 == floorTop) //if moveDiv is ON the floor
{
velocity_x = velocity_x*(1-friction);
moveDiv.style.left = presentLeft + velocity_x;
console.log("on the floor");
console.log("friction is " + friction);
console.log(" and velocity_x is " + velocity_x);
console.log("moveDiv.style.left is " +moveDiv.style.left);
if (velocity_x <= 1)
{
console.log("stopped moving");
moving = false;
}
}
else //if moveDiv will hit the floor/go through the floor this time
{
var diff = floorTop - (presentTop + 100);
moveDiv.style.top = presentTop + diff;
moveDiv.style.left = presentLeft + velocity_x;
}
}
else if (moving == false)
{
clearTimeout(runAgain);
console.log("else if moving == false");
return false;
}
var runAgain = setTimeout("gameLoop()", 5);
//console.log("end of gameLoop");
return false;
}//end gameLoop
function reset () {
moving = false;
moveDiv.style.left=400;
moveDiv.style.top=50;
floorDiv.style.left=200;
floorDiv.style.top=400;
}//end reset
Code for the rotation-test(just the html file and the rotation plugin)
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="jquery.rotate.1-1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#hide").click(function() {
$("p").hide(500);
$(".box").animate({height:300, opacity:0}, 1000);
});
$("#show").click(function() {
$("p").show(500);
$(".box").animate({height:100, opacity:100}, 1000);
});
$(".box").mouseenter(function() {
$(".box").animate({height:300, opacity:0}, 500);
});
$(".box").mouseleave(function() {
$(".box").animate({height:100, opacity:10}, 1000);
});
$("#move").click(function() {
$("#grey").animate({left: -300, top: -100}, 1000)
.animate({left: -600, top: 200}, 1000);
});
$("#cannonball").click(function() {
$("#cannonball").animate({"left": "+=300", "top": "-=100"}, 500)
.animate({"left": "+=300", "top": "+=100"}, 500);
});
$("p.fading").css("opacity","0.3");
$("p.fading").hover(function() {
$(this).stop().animate({opacity: 1.0}, "slow");},
function () {
$(this).stop().animate({opacity: 0.3}, "slow");
});
$("#rotateRight").click(function() {
$("#cannonball").rotate(10);
});
}); //end jquery document.ready scripts
function initialize () {
document.getElementById('box').style.top = 250;
}
</script>
<style type="text/css">
body {
background-color: #ccc;
}
.box {
background-color: #000;
width:100px;
height:100px;
margin-left:300px;
}
.divMove {
position:relative;
top:350px;
float:right;
background-color: #ddd;
width:100px;
height:100px;
margin-right:100px;
}
#cannonball {
position: relative;
}
</style>
</head>
<body onload="initialize();">
<p>Let's make this disappear and appear.</p>
<button id="hide">Hide</button>
<button id="show">Show</button>
<button id="move">Move</button>
<button id="rotateRight">Rotate+</button>
<div id="box" class="box">
</div>
<div class="divMove" id="grey">
</div>
<img src="http://dl.dropbox.com/u/18833130/Webprogrammering/test/cannonball.png" id="cannonball" border="1" />
<p class="fading">This is a paragraph that fades. Let's see how it looks.</p>
</body>
</html>
I apologize for the long post and the amount of code, but if you want to try it you can basically just copy-paste, and I thought it would be easier to discuss this way!
I'm thinking I'll make two different cannon objects, the cannon "base" and the cannon barrel. Then I could just rotate the cannon barrel when the player presses a key. Unfortunately rotation seems to be hard in webprogramming.
The easiest (now) would be to use the CSS transform property:
const angleInputElement = document.getElementById('angle');
const degrees = angleInputElement.value;
const barrelElement = document.getElementById('barrel'); // I don't see this in your sample though
barrelElement.style.transform = `rotate(${degrees}deg)`;
Also, if I want to animate several objects at the same time, do you think I should just change all the objects in the same gameloop function? Any ideas on this?
For this simple implementation that should work fine.

Categories