Wie kann man eine Animationen in JavaScript machen?
Hallo.
ich habe jetzt schon ein bisschen programmiert, aber habe ein Problem.
Ich habe eine Animation gemacht, sodass sich etwas bewegt. Ich will aber auch, dass es sich gleichzeitig dreht. Aber man kann nur eine Animation in CSS haben.
Deshalb muss ich wissen, wie man eine Animation in JavaScript macht.
Hier ist mein Beispiel:
#c {
position: absolute;
width: 50px;
height: 50px;
animation: rotate 5s 1 5s;
animation: hei 5s 1 0s linear forwards;
}
@keyframes hei {
11% { transform: translate(0px, 0px) }
22% { transform: translate(510px, 0px) }
33% { transform: translate(510px, 80px) }
44% { transform: translate(308px, 80px) }
55% { transform: translate(308px, 145px) }
66% { transform: translate(580px, 145px) }
77% { transform: translate(580px, 0px) }
88% { transform: translate(580px, 145px); }
95% { transform: translate(500px, 145px); }
100% { transform: translate(500px, 260px); }
}
@keyframes rotate {
0% { transform: rotate(0deg) }
50% { transform: rotate(160deg) }
100% { transform: rotate(300deg) }
}
Das sind die zwei Animationen.
2 Antworten
Ich denke, dass du dein Problem noch immer mit CSS lösen kannst. Schachtel deine HTML-Struktur an der Stelle.
<div id="c">
<div>
<!-- your content ... -->
</div>
</div>
Die äußere Box nimmt die Verschiebeanimation vor und die innere die Rotation.
#c {
/* ... */
animation: hei 5s 1 0s linear forwards;
}
#c > div {
animation: rotate 5s 1 5s;
}
Bei JavaScript-Animationen würde ich an deiner Stelle erst überlegen, ob es sich um eine Aktion im DOM handeln soll oder ob es nicht sinnvoller wäre, sie auf einem canvas-Element (siehe Canvas API) zu produzieren.
Bei einer Aktion im DOM kann man die setInterval-Funktion nutzen.
setInterval(function() {
/* one animation step ... */
}, 1000);
Das zweite Argument definiert die Dauer eines Intervalls. Die Einheit beträgt hierbei Milisekunden, wobei 1000ms genau eine Sekunde ergeben.
Ein Dokument mit rotierender Box könnte so aussehen:
<!doctype html>
<head>
<title>Example</title>
<style>
#box {
background: red;
height: 50px;
width: 50px;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
function rotate() {
const box = document.getElementById("box");
let rotation = 0;
setInterval(function() {
box.style.transform = `rotate(${rotation}deg)`;
rotation = ++rotation > 360 ? 0 : rotation;
}, 10);
}
rotate();
</script>
</body>
Doch auch hier würde ich eine Verschachtelung im HTML vornehmen, damit sich CSS-Animation und Skript nicht beim Definieren des transform-Property überschneiden.
Danke es hat mier sehr geholfen. Das war eine sehr gute ide :)
Aber man kann nur eine Animation in CSS haben
Wäre mir neu. Denn:
animation-name: fadeInOut, moveLeft300px, bounce;
animation-duration: 2.5s, 5s, 1s;
animation-iteration-count: 2, 1, 5;
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Animations/Using_CSS_animations