Canvas How to - Create a Dropping ball








Question

We would like to know how to create a Dropping ball.

Answer


<!--  w  w  w .  j a  v  a 2  s .  c o m-->
<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
canvas {
  border: 1px solid #f00;
}
</style>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
var speed = 10;
var xv = 2;
var yv = 1;
var gravity = 2;
var circlex = 30;
var circley = 30;
var frames = 1000 / 60;
var friction = 0.95;
var circle = {
    draw: function(x, y, r) {
        ctx.beginPath();
        ctx.arc(x, y, r, 0, Math.PI * 2);
        ctx.closePath();
        ctx.fill();
    }
};
setInterval(function() {
    ctx.clearRect(0, 0, 200, 200);
    speed = speed * friction;
    if (speed < 0.01) {
        speed = 0;
    }
    yv += gravity;
    circlex += xv * speed;
    circley += yv * speed;
    if (circley >= 195) {
        circley = 195;
        yv *= -1;
    }
    if (circlex >= 195) {
        xv *= -1;
        circlex = 195;
    }
    if (circlex <= 5) {
        xv *= -1;
        circlex = 5;
    }
    circle.draw(circlex, circley, 10);
}, frames);
}//]]>  
</script>
</head>
<body>
  <canvas id="c" width="200" height="200"></canvas>
</body>
</html>

The code above is rendered as follows: