Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

182
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!