JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html>
<head>
<title>DXC ..</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id='container'> </div>
<script src="js/init.js"></script>
<script src="js/obj.js"></script>
<script src="js/main.js"></script>
</body>
</html>
CSS
html, body{
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
#container{
position: relative;
width: 100%;
height: 100%;
}
canvas{
position: absolute;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
p{
color: rgb(79, 28, 197);
}
JavaScript
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
var container = document.getElementById("container");
canvas.width = 800;
canvas.height = 480;
canvas.style.border = "solid 1px black";
container.appendChild(canvas);
let player = {
width: 30,
height: 60,
x: 0,
y:110,
color: "rgb(79, 28, 197)",
direction: function(){
if (player.x >= canvas.width - (player.width /2)){
left = true;
}else if (player.x <= 0 - (player.width /2)){
left = false;
}
let movingLeft = left ? player.x -= speed : player.x += speed;
}
};
let ground = {
width: canvas.width,
height: 60,
x: 0,
y:420,
color: "rgb(0, 145, 7)",
};
let left = false;
let speed = 5;
let falling = true;
let jumping = false;
let velocity = 15;
let jumpLimit = 0;
document.addEventListener("DOMContentLoaded", function(){
console.log("loaded");
},false);
function update(progress) {
playerMove();
checkFalling();
collision();
isJumping();
}
function draw() {
context.fillStyle = player.color;
context.clearRect(0, 0, canvas.width, canvas.height)
context.fillRect(player.x, player.y, player.width, player.height);
context.fillStyle = ground.color;
context.fillRect(ground.x, ground.y, ground.width, ground.height);
context.fillRect(100, 300, 100, 30);
}
function playerMove(){
player.direction();
}
function changeDirection(){
if (player.x >= canvas.width - (player.width /2)){
left = true;
}else if (player.x <= 0 - (player.width /2)){
left = false;
}
}
function collision(){
if(falling){
if (player.y + (player.height / 2) >= (ground.y - ground.height/2)){
falling = false;
player.y = ground.y - ground.height ;
}
}
}
function checkFalling(){
if (falling){
player.y += velocity;
}
}
let jump = document.addEventListener("keypress", function(e){
console.log(jumping);
if(e.keyCode == 32 && !jumping && !falling ){
jumping = true;
}
},false);
function...