JavaScript|setInterval()の利用
2021年12月3日今回はsetInterval()を利用してボールを動かしたりバウンドを表現する方法をご紹介します。
動画1:HTMLの作成
動画2:setInterval()を利用してボールを動かす
動画3:ボールの加速の表現と減速の表現
動画4:ボールのバウンドを表現する
<!DOCTYPE html>
<html lang=”ja”>
<meta charset=utf-8>
<body>
<style>
#ball{position:absolute; left:50px; top:30px; width:10px;
height:10px; border-radius:5px; background:red;}
#ground{position:absolute; left:0; top:200px; width:100%;
height:10px; background:#963;}
</style>
<div id=”ball”></div>
<div id=”ground”></div>
<script src=”https://code.jquery.com/jquery-3.6.0.min.js”></script>
<script>
$(function(){
x=50; y=30; movey=5; movex=5;
setInterval(“a()”,80); //100mm秒(0.1)
});
function a(){
x=x+movex;
movey=movey+2;
y=y+movey;
if(y>190){Y=190; movey=movey*-0.8;}
$(“#ball”).css(“left”,x);
$(“#ball”).css(“top”,y);
}
</script>