JSFiddle - React, Tailwind, and code Playground
by Darby Rathbone
CSS
canvas{
width:100%;
height:100%;
}
body,html{
height:100%;
width:100%;
overflow:hidden;
}
*{
margin:0px;
padding:0px;
}
JavaScript
var canvas = document.getElementsByTagName('canvas')[0];
canvas.width = parseInt(getComputedStyle(canvas).width);
canvas.height = parseInt(getComputedStyle(canvas).height);
var ctx = canvas.getContext('2d');
var ball = function(){
var _ball = Object.create(null);
_ball.position = point(50,50);
_ball.velocity = point(0,0);
_ball.radius = 10;
_ball.force = Object.create(point(0,0));
_ball.draw = function(){
ctx.beginPath();
ctx.arc(this.position.x, this.position.y, this.radius, 0, 2 * Math.PI, false);
ctx.fillStyle = 'green';
ctx.fill();
ctx.lineWidth = 1;
ctx.strokeStyle = '#003300';
ctx.stroke();
};
_ball.applyForce = function(f){
this.force.x += f.x;
this.force.y += f.y;
};
_ball.update = function(){
this.velocity.x +=this.force.x;
this.velocity.y +=this.force.y;
this.position.x+= this.velocity.x;
this.position.y+= this.velocity.y;
this.force = point(0,0);
};
_ball.keepWithinBounds = function(){
var x =0;
var y = 0;
if (this.position.x-this.radius<0)
{x = this.velocity.x*-2;
this.position.x=this.radius;
x = Math.abs(x)}
if(this.position.x+this.radius>canvas.width)
{x = this.velocity.x*-2
this.position.x=canvas.width-this.radius;
x =-Math.abs(x)}
if(this.position.y-this.radius<0)
{y = this.velocity.y*-2;
this.position.y=this.radius;
y = Math.abs(y)}
if(this.position.y+this.radius >canvas.height)
{y = this.velocity.y*-2;
this.position.y=canvas.height-this.radius;
y = -Math.abs(y)}
this.applyForce(point(x,y));
};
return _ball;
}
var point = function(x,y){
var _point = Object.create(null);
_point.x = x;
_point.y=y;
_point.add = function(){
var args = [].slice.call(arguments);
args.forEach(function(e){this.x+=e.x;this.y+=e.y;});
return this;
};
_point.sub = function(){
var args = [].slice.call(arguments);
...