JSFiddle - React, Tailwind, and code Playground
by hustlerinc
HTML
<!DOCTYPE HTML>
<html>
<body onload="init();">
<div id="gameArea">
<canvas id="viewport" width="400" height="300"></canvas>
</div>
</body>
</html>
CSS
html,body{width:100%;height:100%;margin:0px;}
#gameArea{width:400px;height:300px;margin:0px auto;}
#viewport{border:1px solid #000;margin:5px 0px 0px;}
JavaScript
var viewport = document.getElementById('viewport');
var ctx = viewport.getContext('2d');
console.log(ctx);
var fps = 30;
function init(){
defaultBalls();
setInterval(gameUpdate, 1000 / fps);
}
function gameUpdate(){
ctx.clearRect(0, 0, viewport.width, viewport.height);
drawBalls();
}
function Ball(X, Y, radius, color){
this.X = X || 0;
this.Y = Y || 0;
this.radius = 10;
this.color = color;
}
Ball.prototype.draw = function(){
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.X, this.Y, this.radius, 10, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
}
Ball.prototype.select = function(mX, mY){
return (this.X - this.radius <= mX) && (this.X + this.radius >= mX)
&& (this.Y - this.radius <= mY) && (this.Y + this.radius >= mY)
}
var balls = [];
function drawBalls(){
for(i=0;i<balls.length;i++){
balls[i].draw();
}
if(ball.length > 0){
for(i=0;i<ball.length;i++){
ctx.strokeStyle = '#01C3F9';
ctx.lineWidth = 3;
ctx.beginPath();
ctx.arc(ball[i].X, ball[i].Y, ball[i].radius, 10, 0, Math.PI*2, true);
ctx.closePath();
ctx.stroke();
}
}
}
function defaultBalls(){
addBall(new Ball(50, 50, 5, '#6B7E00'));
addBall(new Ball(150, 50, 5, '#6B7E00'));
addBall(new Ball(100, 100, 5, '#6B7E00'));
}
function addBall(ball){
balls.push(ball);
}
function selectBall(){
var mX = mouseX;
var mY = mouseY;
for(i=0;i<balls.length;i++){
if(balls[i].select(mX, mY)){
ball.length = 0;
ball.push(balls[i]);
/* Uncomment this to see that click actually happens.
alert('Ball ' + i + ' clicked');
*/
}
/* Uncomment this to get the bug.
else {
ball.length = 0;
}
*/
}
}
function selectedBall(){
for(i=0;i<ball.length;i++){
ball[i].X += 10;
...