Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!doctype html>
- <html>
- <head>
- <script>
- var e = 0.8;
- var canvas;
- var ctx
- var width;
- var height;
- var ball;
- function init(){
- initStage();
- setInterval(onDraw, 20);
- }
- function initStage(){
- canvas = document.getElementById("canvas");
- ctx = canvas.getContext("2d");
- canvas.width = document.width - 100;
- canvas.height = document.height - 100;
- width = canvas.width;
- height = canvas.height;
- ctx.strokeStyle = "blue";
- ball = new Ball();
- }
- function onDraw (){
- canvas.width = canvas.width;
- ball.update();
- }
- function degToRad(deg){
- return (Math.PI / 180) * deg;
- }
- function Ball(){
- this.x = width / 2;
- this.y = height / 2;
- this.vx = 10;
- this.vy = -5;
- this.ax = 0;
- this.ay = 1;
- this.radius = 15;
- this.lineWidth = 5;
- this.update = function(){
- this.updatePhysics();
- this.redraw();
- }
- this.updatePhysics = function(){
- this.x += this.vx;
- this.vx += this.ax;
- this.y += this.vy;
- this.vy += this.ay;
- if(this.x - this.radius < 0 || this.x + this.radius > width){
- if(this.x - this.radius < 0){
- this.x = this.radius;
- }else{
- this.x = width - this.radius;
- }
- this.vx *= -1 * e;
- }
- else if(this.y - this.radius < 0 || this.y + this.radius > height){
- if(this.y - this.radius < 0){
- this.y = this.radius;
- }
- else{
- this.y = height - this.radius;
- }
- this.vy *= -1 * e;
- }
- }
- this.redraw = function(){
- ctx.beginPath();
- ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, true);
- ctx.closePath();
- ctx.lineWidth = this.lineWidth;
- ctx.stroke();
- }
- }
- </script>
- </head>
- <body onload=init()>
- <canvas id="canvas" width="500" height="500" style="border: 1px gray solid"/>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement