用html5中canvas實現的彈跳小球
<!DOCTYPE><html>
<head>
<title>canvas 測試案例二:彈球游戲</title> <style> </style>
</head>
<body>
<canvas id="canvas" class="canvas" width='400px' height='300px'>Your browser does not support the HTML5 element canvas</canvas> <script> var boxX = 20, boxY = 30, //盒子的左上角 x y 的初始位置 boxWidth = 350, boxHeight = 250, //盒子的寬高 ballRad = 10, // 球的半徑 boxRoundX = boxWidth boxX - ballRad, //右邊界 boxRoundY= boxHeight boxY - ballRad, //下邊界 inboxRoundX = boxX ballRad, //左邊界 inboxRoundY= boxY ballRad, // 上邊界 ballX = 50, ballY = 60, //球的初始位置 ballVX = 4, //初始水平位移 ballVY= 8; //初始垂直位移 function init () { var ctx = document.getElementById('canvas').getContext('2d'); ctx.linewidth = ballRad; ctx.fillStyle = 'rgb(200, 0, 50)'; moveBall(); setInterval(moveBall, 25); // 移動球的函數 function moveBall () { ctx.clearRect(boxX, boxY, boxWidth, boxHeight); changDirect(); ctx.beginPath(); ctx.arc(ballX, ballY, ballRad, 0, Math.PI * 2, false); ctx.fill(); ctx.strokeRect(boxX, boxY, boxWidth, boxHeight); } // 判斷距離方向函數 function changDirect () { var nextX = ballX ballVX, nextY = ballY ballVY; if (nextX > boxRoundX) { ballVX = -ballVX; nextX = boxRoundX; } if (nextX < inboxRoundX) { ballVX = -ballVX; nextX = inboxRoundX; } if (nextY > boxRoundY) { ballVY = -ballVY; nextY = boxRoundY; } if (nextY < inboxRoundY) { ballVY = -ballVY; nextY = inboxRoundY; } ballX = nextX; ballY = nextY; } } init(); </script>
</body>
</html></pre>來自:https://github.com/chenkehxx/practice/commit/65067f7bb7948abe94b052f3e69fc2b1892ab167
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!