Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

192
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda