Search code examples
javascripthtmlcoordinatesmouseeventdrawing

JavaScript - Drawing a circle/dot with each click depending on the coordinates


I want to be able to paint or draw a circle/dot every time the user clicks inside a rectangle. It should be possible to add as many circles/dots as there are clicks and their position changes depending on the coordinates where the click was made. This is the code I'm using:

Circle:

 <circle cy="50" cx="50" r="30" fill="#f"></circle>

Code that I'm using: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_event_mouse_clientxy2

What should I add in this code so it does what I want?


Solution

  • You need to add the <circle> tag in an <svg> tag.

    const svg = document.querySelector('svg');
    
    svg.addEventListener('click', e => {
      const { pageX, pageY, currentTarget } = e;
      const { left, top } = currentTarget.getBoundingClientRect();
      const { pageXOffset, pageYOffset } = window;
      const x = pageX - left - pageXOffset;
      const y = pageY - top - pageYOffset;
      const diameter = Math.floor(Math.random()*100);
      
      svg.innerHTML += createCircle({ x, y }, diameter);
    });
    
    function createCircle(center, diameter) {
        const randomColor = Math.floor(Math.random()*16777215).toString(16);
    
        return `
        <circle
            cx="${center.x}"
          cy="${center.y}"
          r="${diameter/2}"
          fill="#${randomColor}"
        ></circle>
      `;
    }
    .container {
      border: 1px solid #000;
      height: 300px;
      width: 500px;
    }
    
    svg {
      height: 100%;
      width: 100%;
    }
    <div class="container">
      <svg xmlns="http://www.w3.org/2000/svg"></svg>
    </div>

    Also, changed the clientX/Y properties to consider the container, window offsets/coordinates for scroll compatibility.