JSFiddle - React, Tailwind, and code Playground

by forresto

HTML

<!-- game canvas -->
<canvas id="drawing"></canvas>
<!-- scoreboard -->
<div id="points">0</div>

CSS

#points {
    text-align: center;
}

JavaScript

var canvas = document.getElementById("drawing");
context = canvas.getContext("2d");

// p.size(400, 400);
canvas.width = 400;
canvas.height = 400;

// If you want to use mouseX and mouseY
var mouseX = 0;
var mouseY = 0;
canvas.onmousemove = function (e) {
    mouseX = e.pageX - this.offsetLeft;
    mouseY = e.pageY - this.offsetTop;
};

// If you want to use mousePressed
var mousePressed = false;
canvas.onmousedown = function (e) {
    mousePressed = true;
};
canvas.onmouseup = function (e) {
    mousePressed = false;
};

// If you want to use these mouse variables with touchscreens as well
canvas.ontouchmove = function (e) {
    e.preventDefault();
    // Just looks at first finger
    mouseX = e.targetTouches[0].pageX - canvas.offsetLeft;
    mouseY = e.targetTouches[0].pageY - canvas.offsetTop;
}
canvas.ontouchstart = function (e) {
    mousePressed = true;
    canvas.ontouchmove(e);
};
canvas.ontouchend = function (e) {
    mousePressed = false;
};



var GRAVITY = 0.1;

var player = {};
player.x = canvas.width / 2;
player.y = canvas.width / 2;
player.speed = 0;

var drawPlayer = function (x, y) {
    context.fillStyle = "white";
    context.fillRect(x, y, 50, 50);
    context.strokeStyle = "blue";
    context.strokeRect(x, y, 50, 50);
    context.strokeRect(x + 10, y + 10, 10, 10);
    context.strokeRect(x + 30, y + 10, 10, 10);
};

var gameOver = function () {
    player.y = canvas.width / 2;
    player.speed = 0;
    points = 0;

    context.fillStyle = "red";
    context.fillRect(0, 0, canvas.width, canvas.height);
    playing = false;
};

var points = 0;
var playing = false;

var enemies = [];
for(var i = 0; i<10; i++){
    var enemy = {};
    enemy.x = canvas.width + Math.random() * canvas.width;
    enemy.y = Math.random() * canvas.height;
    enemy.speed = -1;
    enemies.push(enemy);
}

var gameTick = function () {
    var acceleration = GRAVITY;
    if (mousePressed) {
        acceleration = -GRAVITY;
    }
    player.speed += acceleration;
   ...