2
I’m trying to make an animation with pure javascript, and I’m using style.transform = "rotate(" + ang + "deg)";
to do this. My intention is: when it reaches an x position, it goes back counterclockwise. It goes clockwise but does not change at the time of returning, I tried 1000 thing but n.
Follow the full code of the html file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<style>
#div{
width: 100px;
height: 100px;
border: 1px solid black;
background-color: blue;
position: absolute;
left: 0;
top: 0;
}
</style>
<script>
let jog, vel, dx, px, anima, parar, anima2, ang, rotacao;
function inicia(){
jog = document.getElementById("div");
vel = 2;
px = 0;
dx = 1;
ang = 0;
parar = true;
jog.addEventListener("click", moverParar);
game();
}
function moverParar(){
if(parar){
parar = false;
cancelAnimationFrame(anima);
}else{
parar = true;
anima = requestAnimationFrame(game);
}
}
function gira(){
jog.style.transform = "rotate(" + ang + "deg)";
rotacao = ang++;
if(px > 500){
dx = -1;
ang = 360;
rotacao = ang--;
}
else if(px < 0){
dx = 1;
ang = 0;
rotacao = ang++;
}
//anima2 = requestAnimationFrame(gira);
}
function game(){
px += dx * vel;
jog.style.left = px + "px";
gira();
anima = requestAnimationFrame(game);
}
window.addEventListener("load", inicia);
</script>
<body>
<div id="div"></div>
</body>
</html>
Thank you so much for your help, hugs!
– Erick Ferrara Bazan
So I didn’t even need to use the rotation variable right, just use ang and direction.
– Erick Ferrara Bazan