JSFiddle - React, Tailwind, and code Playground
by centerwow
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;
var instructions = "Click the ball!";
var target;
function init(){
setInterval(update, 1000 / fps);
}
function update(){
ctx.clearRect(0, 0, 400, 300);
draw();
moveBall();
targetBall();
}
function Ball(){
this.X = 50;
this.Y = 50;
this.radius = 10;
}
var ball = new Ball();
ball.color = '#FA9E00';
ball.stroke;
function moveBall(){
if(mouseX && mouseY){
var newX = mouseX;
var newY = mouseY;
}
if(target == 1){
if(ball.X < newX){
ball.X++;
}
if(ball.Y < newY){
ball.Y++;
}
if(ball.X > newX){
ball.X--;
}
if(ball.Y > newY){
ball.Y--;
}
}
}
function targetBall(){
if(mouseX && mouseY){
if(mouseX <= (ball.X + ball.radius)
&& mouseX >= (ball.X - ball.radius)
&& mouseY <= (ball.Y + ball.radius)
&& mouseY >= (ball.Y - ball.radius)){
target = 1;
instructions = "Good, now click anywhere on the canvas.";
}
}
}
function draw(){
ctx.fillStyle = ball.color;
ctx.beginPath();
ctx.arc(ball.X, ball.Y, ball.radius, 10, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
if(target == 1){
ctx.strokeStyle = '#01C3F9';
ctx.lineWidth = 3;
ctx.beginPath();
ctx.arc(ball.X, ball.Y, ball.radius, 10, 0, Math.PI*2, true);
ctx.closePath();
ctx.stroke();
}
ctx.font = 'bold 16px Arial';
ctx.fillStyle = '#0f0';
ctx.fillText(instructions, 75, 50);
}
function findPos(obj)
{
var curleft = curtop = 0;
if (obj.offsetParent)
{
do
{
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
}
while (obj = obj.offsetParent);
}
return [curleft,curtop];
}
CO = findPos(viewport); //CO stands for canvas offset
var mouse = [0, 0];
var mouseX;
function onclick(e)
{
mouseX = e.pageX - self.CO[0];
mouseY =...