Home > Back-end >  Add dot on canvas grid
Add dot on canvas grid

Time:03-31

This is a canvas grid with the coordinates labelled when you click on the grid at

enter image description here

function showCoords(event) {
    var x = event.clientX - 10;
    var y = event.clientY - 10;
    var coords = "X coordinates: "   x   ", Y coordinates: "   y;
    document.getElementById('showCoords').innerHTML = coords;

  }

CodePudding user response:

OK so first you may create a CSS class for the red dots:

  <style>
    .red-dot {
      position:absolute; 
      width:5px; 
      height:5px;
      background:red;
    }
  </style>

Then try to modify the showCoords() method:

function showCoords(event) {
    // Calculate the position of the nearest grid intersection:
    var x = (Math.floor(event.clientX/10) * 10) - 2;
    var y = (Math.floor(event.clientY/10) * 10) - 2;
    var coords = "X coordinates: "   x   ", Y coordinates: "   y;
    document.getElementById('showCoords').innerHTML = coords;
    // Create a new red dot:
    let newDot = document.createElement('span');
    // Add the CSS class:
    newDot.className = 'red-dot';
    // Set coordinates:
    newDot.style.top = y   'px';
    newDot.style.left = x   'px';
    // Add the new element to the end of the body:
    document.body.appendChild(newDot);
  }
  • Related