Canvas with key events

by sungsoonz

HTML

<canvas id="canvas"></canvas>

CSS

#canvas {
  background: #000;
}

JavaScript

window.activeKey = {};

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

let character = null;
let particles = [];

function init() {
  character = new Character(ctx, canvas.width / 2, canvas.height / 2, 10);
  eventSetting();
  render();
}

function eventSetting() {
  window.addEventListener('keydown', (e) => {
    activeKey[`${e.key}`] = true;
  });
  window.addEventListener('keyup', (e) => {
    activeKey[`${e.key}`] = false;
  });
}

window.addEventListener('keydown', makeParticles);
window.addEventListener('keyup', handleParticles);

function makeParticles() {
  for (let i = 0; i < 10; i++) {
    particles.push(new Particle(ctx, character.position.x, character.position.y, 2));
  }
}

function handleParticles() {
  for (let i = 0; i < particles.length; i++) {
    let particle = particles[i];
    particle.update();
  }
}

function render() {
  ctx.clearRect(0,0,canvas.width,canvas.height);
  character.update();
  character.draw();
  handleParticles();
  requestAnimationFrame(render);
}


class Position {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  set(x, y) {
    if (x != null) {
      this.x = x
    };
    if (y != null) {
      this.x = y
    };
  }
}

class Character {
  constructor(ctx, x, y, size) {
    this.ctx = ctx;
    this.size = size;
    this.position = new Position(x,y);
  }
  update() {
    if (activeKey.ArrowUp === true) {
      this.position.y -= 3;
    }
    if (activeKey.ArrowLeft === true) {
      this.position.x -= 3;
    }
    if (activeKey.ArrowDown === true) {
      this.position.y += 3;
    }
    if (activeKey.ArrowRight === true) {
      this.position.x += 3;
    }
  }
  draw(x,y,size) {
  	let nowX = x || this.position.x;
    let nowY = x || this.position.y;
    let nowSize = x || this.size;
    this.ctx.beginPath();
    this.ctx.arc(this.position.x,this.position.y, this.size, 0, Math.PI*2);
    this.ctx.fillStyle = 'red';
    this.ctx.fill();
  }
}

class Particle extends...