Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <canvas id="canvas"></canvas>
</body>
</html>
 
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = 400;
canvas.height = 300;
const gravity = 2;
class Main {
  constructor(x, y, w, h) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.lives = 3;
    this.speedX = 0.5;
    this.speedY = 35;
    this.jumping = false;
    this.vx = 0;
    this.vy = 0;
  }
  draw() {
    ctx.beginPath();
    ctx.rect(this.x, this.y, this.w, this.h);
    ctx.fill();
    ctx.closePath();
  }
  canvasCollision() {
    if (this.x <= 0) this.x = 0;
    if (this.y <= 0) this.y = 0;
    if (this.x + this.w >= canvas.width) this.x = canvas.width - this.w;
    if (this.y + this.h >= canvas.height) {
      this.y = canvas.height - this.h;
      this.vy = 0;
      this.jumping = false;
    }
  }
  update() {
    if (controller1.left) this.vx -= this.speedX;
    if (controller1.up && !this.jumping) {
      this.vy -= this.speedY;
      this.jumping = true;
    }
    if (controller1.right) this.vx += this.speedX;
    this.vy += gravity;
    this.x += this.vx;
    this.y += this.vy;
    this.vx *= 0.9;
    this.vy *= 0.9;
    this.canvasCollision();
  }
}
class Controller {
  constructor() {
    this.up = false;
    this.right = false;
    this.down = false;
    this.left = false;
    let keyEvent = (e) => {
      if (e.code == "KeyW" || e.code == "ArrowUp") {
        this.up = e.type == "keydown";
      }
      if (e.code == "KeyD" || e.code == "ArrowRight") {
        this.right = e.type == "keydown";
      }
      if (e.code == "KeyA" || e.code == "ArrowLeft") {
        this.left = e.type == "keydown";
      }
    };
    addEventListener("keydown", keyEvent);
    addEventListener("keyup", keyEvent);
    addEventListener("mousemove", keyEvent);
  }
}
let main1 = new Main(canvas.width / 2, canvas.height / 2, 50, 50);
let controller1 = new Controller();
function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  main1.update();
  main1.draw();
  requestAnimationFrame(animate);
}
animate();
Output

This bin was created anonymously and its free preview time has expired (learn why). — Get a free unrestricted account

Dismiss x
public
Bin info
anonymouspro
0viewers