JSFiddle - React, Tailwind, and code Playground
by Darby Rathbone
JavaScript
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = (window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
return window.setTimeout(callback, 1000, 60);
});
}
function Ball(radius, color) {
if (radius === undefined) {
radius = 20;
}
if (color === undefined) {
color = "#ff0000";
}
this.x = 0;
this.y = 0;
this.radius = radius;
this.vx = 0;
this.vy = 0;
this.rotation = 0;
this.scaleX = 1;
this.scaleY = 1;
this.color = color;
this.lineWidth = 1;
return this;
}
Ball.prototype.draw = function (context) {
context.save();
context.translate(this.x, this.y);
context.rotate(this.rotation);
context.scale(this.scaleX, this.scaleY);
context.lineWidth = this.lineWidth;
context.fillStyle = this.color;
context.beginPath();
context.arc(0, 0, this.radius, 0, (Math.PI * 2), true);
context.closePath();
context.fill();
if (this.lineWidth > 0) {
context.stroke();
}
context.restore();
};
Ball.prototype.move = function(maxx,maxy,vx,vy){
if (this.x < this.radius)
this.vx+=1;
if (this.x > maxx-this.radius)
this.vx-=1;
if(this.y <this.radius)
this.vy +=1;
if(this.y > maxy-this.radius)
this.vy-=1;
if(!vx) vx =0;
if(!vy) vy =0;
this.vx+=vx;
this.vy+=vy;
this.vx*=.99;
this.vy *=.99;
this.x += this.vx;
this.y += this.vy;
};
var captureMouse = function (element) {
var mouse = {
x: 0,
y: 0
};
element.addEventListener('mousemove', function (event) {
var x, y;
if (event.pageX || event.pageY) {
x = event.pageX;
y = event.pageY;
} else {
x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
y = event.clientY +...