Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

190
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda