JSFiddle - React, Tailwind, and code Playground
HTML
<p><canvas id="canvas" width="500" height="500"></p>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var positionX = 100.0;
var positionY = 350.0;
var velocityX = 4.0;
var velocityY = 0.0;
var gravity = 0.5;
var onGround = false;
window.addEventListener("mousedown", StartJump, false);
window.addEventListener("mouseup", EndJump, false);
Loop();
function StartJump()
{
if(onGround)
{
velocityY = -12.0;
onGround = false;
}
}
function EndJump()
{
if(velocityY < -6.0)
velocityY = -6.0;
}
function Loop()
{
Update();
Render();
window.setTimeout(Loop, 33);
}
function Update()
{
velocityY += gravity;
positionY += velocityY;
positionX += velocityX;
if(positionY > 300.0)
{
positionY = 300.0;
velocityY = 0.0;
onGround = true;
}
if(positionX < 10 || positionX > 500)
velocityX *= -1;
}
function drawSquare() {
ctx.beginPath();
ctx.rect(300, 270, 30, 30);
ctx.fillStyle = "#FF0000";
ctx.fill();
ctx.closePath();
}
function Render()
{
ctx.clearRect(0, 0, 500, 500);
drawSquare();
ctx.beginPath();
ctx.moveTo(0,300);
ctx.lineTo(500, 300);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(positionX - 10, positionY - 20);
ctx.lineTo(positionX + 10, positionY - 20);
ctx.lineTo(positionX + 10, positionY);
ctx.lineTo(positionX - 10, positionY);
ctx.closePath();
ctx.stroke();
}
</script>