Canvas

by LyndseyB

HTML

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

CSS

* { 
  margin:0; 
  padding:0; 
}

html, body { 
  width:100%; 
  height:100%; 
}

canvas {
  display: block;
}

Babel + JSX

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

const GAME = {
	players: [{    
    id: 1,
    name: 'Player 1',
    color: 'red',
    score: 0,      
  },
  {    
    id: 2,
    name: 'Player 2',
    color: 'blue',
    score: 0,     
  }],  
  mouse: {
  	x: null,
    y: null,
    status: {
    	clicked: false,
      clickedLastFrame: false
    },
  },
  positions: [],
  objects: 20,
  scoreMargin: 20,
};

window.addEventListener('resize', draw);

window.addEventListener('mousemove', (e) => {
	GAME.mouse.x = e.clientX;
  GAME.mouse.y = e.clientY;
  GAME.mouse.status.clicked = false;
});

window.addEventListener('mousedown', (e) => {
	GAME.mouse.x = e.clientX;
  GAME.mouse.y = e.clientY;
  GAME.mouse.status.clickedLastFrame = false;
  GAME.mouse.status.clicked = true;
});

window.addEventListener('mouseup', (e) => {
	GAME.mouse.x = e.clientX;
  GAME.mouse.y = e.clientY;
  GAME.mouse.status.clickedLastFrame = true;
  GAME.mouse.status.clicked = false;
});

draw();
createGameObjects(); 
setInterval(gameLoop, 1000 / 30);

function draw() {
	canvas.width = window.innerWidth;
	canvas.height = window.innerHeight;
  
	ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = '#fff';
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  
  drawGame();  
  drawScore();
}

function drawScore() {
	ctx.font = '18px serif';
  ctx.fillStyle = '#000';
  
  const margin = GAME.scoreMargin;
  
  GAME.players.forEach((player, index) => {
  	const playerTxt = `${player.name}: ${player.score}`;
    ctx.fillText(playerTxt, margin, (margin * ++index));
  });
}

function createGameObjects() {
	let counter = 0;
  
  GAME.players.forEach((player) => { 
    while(counter < GAME.objects) {
      const position = { 
      	fill: player.color,
        player: player.id,
        ...createPosition(),
     	};

      GAME.positions.push(position);      
      counter++;
    }
    counter = 0;
  });
}

function random(min, max) {
	return...