Lær at oprette HTML-animationer ved hjælp af JavaScript.
For at demonstrere, hvordan man laver HTML-animationer med JavaScript, vil vi bruge en simpel hjemmeside:
<!DOCTYPE html>
<html>
<body>
<h1>My First
JavaScript Animation</h1>
<div id="animation">My animation will go here</div>
</body>
</html>
Alle animationer skal være i forhold til et containerelement.
<div id ="container">
<div id ="animate">My
animation will go here</div>
</div>
Containerelementet skal oprettes med style="position: relativ
".
Animationselementet skal oprettes med stil="position: absolut
".
#container {
width: 400px;
height:
400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height:
50px;
position: absolute;
background: red;
}
Prøv det selv →
<!Doctype html>
<html>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background: red;
}
</style>
<body>
<h2>My First JavaScript Animation</h2>
<div id="container">
<div id="animate"></div>
</div>
</body>
</html>
JavaScript-animationer udføres ved at programmere gradvise ændringer i et elements stil.
Ændringerne kaldes af en timer. Når timerintervallet er lille, vil animationen ser kontinuerlig ud.
Den grundlæggende kode er:
id = setInterval(frame, 5);
function frame() {
if (/*
test for finished */) {
clearInterval(id);
} else {
/* code to change the element style */
}
}
function myMove() {
let id = null;
const elem = document.getElementById("animate");
let pos = 0;
clearInterval(id);
id = setInterval(frame, 5);
function frame() {
if (pos ==
350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
Prøv det selv →
<!DOCTYPE html>
<html>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
</style>
<body>
<p><button onclick="myMove()">Click Me</button></p>
<div id ="container">
<div id ="animate"></div>
</div>
<script>
function myMove() {
let id = null;
const elem = document.getElementById("animate");
let pos = 0;
clearInterval(id);
id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + "px";
elem.style.left = pos + "px";
}
}
}
</script>
</body>
</html>