Skip to content

Instantly share code, notes, and snippets.

@memish
Last active September 8, 2017 00:58
Show Gist options
  • Save memish/5f07f459e1fcd2fbaff43781d512b750 to your computer and use it in GitHub Desktop.
Save memish/5f07f459e1fcd2fbaff43781d512b750 to your computer and use it in GitHub Desktop.
<html lang=en>
<head>
<meta charset=utf-8>
<title>Javascript gravity</title>
<style>
* { padding: 0; margin: 0; }
canvas { background: #eee; display: block; margin: 0 auto; }
</style>
</head>
<body onload="init()">
<canvas id="myCanvas" width="680" height="420"></canvas>
<script>
var canvas, ctx;
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
/* *****************
Class Variables
**********************/
var ball;
var message = "gravity simulator";//text that will appear on the page
var vx = 0;// Velocity x - initially set to zero
var vy = 0; // Velocity y - initially set to zero
var counter =0;//time elapsed
/* *****************
Initial state of program
**********************/
function init(){
vy = (Math.random() * 15) + 5;//randomly assigning value
//starting point, color and radius for ball
ball = {x:canvas.width / 2, y:200, radius:20, status: 0, color:"red"};
}//end init method
/* *****************
display some text
**********************/
function displayText(){
ctx.fillStyle = "blue";
ctx.font = "20px Arial";
ctx.fillText(message, 20,20);
}
/* *****************
draw the ball
**********************/
function drawBall(){
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI*2, false);
ctx.fillStyle = ball.color;
ctx.fill();
ctx.closePath();
}
/* *****************
place your methods in here
**********************/
function draw() {
ctx.clearRect(0,0,canvas.width, canvas.height);
displayText();
drawBall();
counter++;
}
setInterval(draw, 1000/35);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment