JSFiddle - React, Tailwind, and code Playground

by ysis81

HTML

<canvas id="game" width="481" height="481">
</canvas>
<br>
<br>
<span id="bordertop"></span>
<span id="borderleft"></span>
<span id="xcoord"></span>
<span id="ycoord"></span>

CSS

#game {
  display: block;
  position: relative;
  margin: 0 auto;
  background: #808080;
  border: 10px solid black;
  z-index: 0;
}

JavaScript

// 2D Canvas and context
  var canvas = document.getElementById('game');
  var context = canvas.getContext('2d');
  var xspan = document.getElementById('xcoord');
  var yspan = document.getElementById('ycoord');
  //var borderleft = document.getElementById('borderleft');
  //var bordertop = document.getElementById('bordertop');

  // Size of canvas
  var width = canvas.width,
    height = canvas.height;

  // Radius of each piece
  var radius = 0.9 * (width - 1) / 16;

  // Allocating piece array
  var arrayCurrent = new Array(8);
  for (i = 0; i < 8; i++)
    arrayCurrent[i] = new Array(8);

  // Board color
  var colorBoard = '#808080';

  // Initialize board
  initBoard();

  // Set event listener
  canvas.addEventListener('mousemove', getPosition, false);

  // Solution 3
  function getPosition(event) {

    var x, y;
    var rect = canvas.getBoundingClientRect();
    var computedStyle = window.getComputedStyle(canvas,null);
    var topBorder = parseInt(computedStyle.getPropertyValue("border-top-width"),10);
    var leftBorder = parseInt(computedStyle.getPropertyValue("border-left-width"),10);
    
    var x = event.clientX - rect.left - leftBorder;
    var y = event.clientY - rect.top - topBorder;
    
    // Display coordinates
    xspan.innerHTML = x;
    yspan.innerHTML = y;
    
  }

  function initBoard() {

    context.strokeStyle = 'white';
    context.lineWidth = 1;

    var centerX, centerY;

    // Drawing main frame
    for (var i = 0; i < 8; i++)
      for (var j = 0; j < 8; j++)
        context.strokeRect(i * (width - 1) / 8 + 0.5, j * (height - 1) / 8 + 0.5, (width - 1) / 8, (height - 1) / 8);

  }