We can bounce the ball using canvas HTML5
<h2 style="color:red;"><b><i>Bouncing ball animation in canvas</i></b></h2> <canvas id="mycanvas" width="400" height="300" style="border:5px solid blue;"></canvas> <script> var canvas = document.getElementById('mycanvas'); var ctx = canvas.getContext('2d'); var p = { x: 25, y: 25 }; var velo = 3, corner = 50, rad = 20; var ball = { x: p.x, y: p.y }; var moveX = Math.cos(Math.PI / 180 * corner) * velo; var moveY = Math.sin(Math.PI / 180 * corner) * velo; function DrawMe() { ctx.clearRect(0, 0, 400, 300); if (ball.x > canvas.width - rad || ball.x < rad) moveX = -moveX; if (ball.y > canvas.height - rad || ball.y < rad) moveY = -moveY; ball.x += moveX; ball.y += moveY; ctx.beginPath(); ctx.fillStyle = 'red'; ctx.arc(ball.x, ball.y, rad, 0, Math.PI * 2, false); ctx.fill(); ctx.closePath(); } setInterval(DrawMe, 10); </script>
"mycanvas"
, width as 400
and height as 300
and we are having the style as border
as 5 px solid blue colorvar canvas = document.getElementById('mycanvas');
- It defines the id as "mycanvas"ar ctx = canvas.getContext('2d');
- It defines the context to the canvas elementvar p = { x: 25, y: 25 };
- It defines we are declaring var as p to x as 25 and y as 25 which defines the xpositions and y positionsv
ar velo = 3, corner = 50, rad = 20;
- It defines the velo as 3 corner, 50 and rad as 20velo
- It defines the different shapes in the canvascorner
- It defines the rotation of the ball animationrad
- It defines the size of the ballball x=p.x
ball y= p.y
var moveX = Math.cos(Math.PI / 180 * corner) * velo;
- It defines the moveX with the given valuesvar moveY = Math.sin(Math.PI / 180 * corner) * velo;
- It defines the moveY with the given valuesctx.clearRect(0, 0, 400, 300);
- It defines the clear rect as (x, y, width, height)
which sets the position n to the centerif (ball.x > canvas.width - rad || ball.x < rad) moveX = -moveX;
- it defines as if the ball.X greater than canvas width(400)-rad(20)||ball.xlessthan rad(20) is equal to -movXif (ball.y > canvas.height - rad || ball.y < rad) moveY = -moveY;
- it defines as if the ball.Y greater than canvas height(400)-rad(20)||ball.Ylessthan rad(20) is equal to -movYball.x += moveX;
- I defines the ball.X to the moveXball.y += moveY;
- It defines the ball.Y to the moveYsetinterval (drawme, 10)
is a function which calls the function (Drawme) with the speed as 10output
Views: 19278 | Post Order: 116