Bipin Prajapati
Bipin Prajapati

Reputation: 13

A simple program to display a rolling ball

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var canvas_variable;
var init_x = 200;
var init_y = 300;
var x_move = 1;
function initialize_canvas()
{setInterval(draw_ball, 10);
 canvas_variable = bouncing_ball_canvas.getContext('2d');
  }
  function draw_ball()
   {
   canvas_variable.clearRect(0,0, 1000, 500);
   canvas_variable.beginPath();
   canvas_variable.fillStyle="#FF0000";
   canvas_variable.arc(init_x, init_y, 50, 0+init_x/50, Math.PI*2+init_x/50, true);
   canvas_variable.lineTo(init_x, init_y);
   canvas_variable.stroke();
   if( init_x<0 || init_x>1000) x_move = -x_move;
   init_x += x_move;
   }
  </script>
  </head>
  <body>
  <canvas id="bouncing_ball_canvas" width="1000" height="500">
  </canvas>
  <body onLoad="initialize_canvas();">
  </body>
  </html>

This is a program of a rolling ball. The function draw_ball is called after every 10 milliseconds.The ball blinks during its motion. What is the solution for this problem?

Upvotes: 0

Views: 1921

Answers (2)

J Cote
J Cote

Reputation: 1

It is blinking because your computation is wrong. You need to compute the perimeter: 2*pi*r. Then do a simple cross product:

distance = x
perimeter = 2*pi

So the angle (in radian) is distance*2*pi/perimeter

So try this:

const getAngle=function(distance) {
    return distance*2*Math.PI/perimeter;
}
const getPos=function(x, y, angle, r) {
    return [x + Math.cos(angle)*r, y + Math.sin(angle)*r];
}
canvas_variable.arc(init_x, init_y, 50, 0, Math.PI*2, true);
canvas_variable.moveTo(..getPos(init_x, init_y, getAngle(init_x-starting_x), r));
canvas_variable.lineTo(init_x, init_y);
canvas_variable.stroke();

Upvotes: 0

Niddro
Niddro

Reputation: 1725

You forgot to declare the variable bouncing_ball_canvas

Try adding:

bouncing_ball_canvas = document.getElementById("bouncing_ball_canvas");

before you declare canvas_variable.

EDIT:

The problem lies in the line:

canvas_variable.arc(init_x, init_y, 50, 0+init_x/50, Math.PI*2+init_x/50, true);

Change the last variable to false and it should work.

Upvotes: 2

Related Questions