JSFiddle - React, Tailwind, and code Playground
by techtiger255
HTML
<body>
<div id="gameContainer" width="480px" height="340px">
<canvas width="480px" height="340px"></canvas>
<div id="resizeBar" title="Resize Game"></div>
</div>
<button id="pause">pause</button>
<button class="difficulty" id="0">easy</button>
<button class="difficulty" id="1">medium</button>
<button class="difficulty" id="2">hard</button>
<button id="reset">reset</button>
</body>
CSS
body {
user-select: none;
}
#gameContainer {
position: relative;
width: 480px;
height: 340px;
margin-bottom: 7px;
min-width: 320px;
min-height: 226.666px;
}
#gameContainer canvas {
background: lightseagreen;
border-radius: 5px;
border: 2px solid slategrey;
resize: "both";
overflow: "hidden";
width: 480px;
height: 340px;
min-width: 320px;
min-height: 226.666px;
}
#resizeBar {
cursor: se-resize;
position: absolute;
right: 0;
bottom: 0;
z-index: 100;
width: 0;
height: 0;
border-style: solid;
border-width: 0 0 11.75px 11.75px;
border-color: transparent rgba(224, 224, 224, 0.5) rgba(224, 224, 224, 0.5)
transparent;
}
JavaScript
//Prefixed variables, extra game mechanics, buttons etc
var canvas = document.getElementsByTagName("canvas")[0],
resizeBar = document.getElementById("resizeBar"),
ctx = canvas.getContext("2d"),
cw = 480,
ch = 340,
killVar = false,
started = false,
paused = false,
previousCursor;
function start(e) {
go(e);
killVar = true;
}
function ratio(total, pixels) {
let div = total;
if (total === canvas.width) div = cw;
if (total === canvas.height) div = ch;
return total * (pixels / div);
}
// External event listeners
(() => {
let buttons = document.getElementsByClassName("difficulty");
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", start);
}
document.getElementById("reset").addEventListener("click", () => {
location.reload();
});
canvas.addEventListener("click", pauseButton);
document.getElementById("pause").addEventListener("click", pause);
window.addEventListener("visibilitychange", pause);
window.addEventListener("blur", pause);
function pause(e = { type: 0 }) {
e.preventDefault ? e.preventDefault() : null;
if (e.type === "visibilitychange") {
paused = document.hidden;
} else if (e.type == "blur" || e.type == "focus") {
paused = e.type == "blur";
} else {
paused = !paused;
}
if (!paused) return;
pauseShape();
}
function pauseShape() {
if (!started || !paused) return;
let topLeftX = cw / 2.5,
topLeftY = ch / 3,
rightX = cw - cw / 2.5,
rightY = ch / 2,
bottomLeftX = cw / 2.5,
bottomLeftY = ch - ch / 3;
ctx.beginPath();
ctx.fillStyle = "deepblue";
ctx.moveTo(topLeftX, topLeftY);
ctx.lineTo(rightX, rightY);
ctx.lineTo(bottomLeftX, bottomLeftY);
ctx.fill();
ctx.closePath();
paused ? requestAnimationFrame(pauseShape) : null;
}
function pauseButton() {
pause();
}
resizeBar.addEventListener("mousedown", initResize, false);
function initResize(e) {
window.addEventListener("mousemove", resize, false);
window.addEventListener("mouseup",...