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

108
Visualizações
How to avoid overlap of randomly generated coordinates in a HTML5 Canvas?

I want to generate a set of text elements inside a triangle bounded by preset coordinates. For example; something like this. Note that the text should be inside the pink triangle. (It is okay if the text clips the triangle's lines since the triangle will be invisible in the final product, this is just for reference)

To achieve this I created the following codepen.

The random generation inside specified boundaries works fine, but since its possible for the same or very close coordinates to be generated, sometimes the text overlaps.

Is there any possible approach I could take to fix/avoid this issue efficiently?

function randomIntFromInterval(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min)
}

function area(x1, y1, x2, y2, x3, y3) {
  return Math.abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0);
}

function isInside(x1, y1, x2, y2, x3, y3, x, y) {
  let A = area(x1, y1, x2, y2, x3, y3);

  let A1 = area(x, y, x2, y2, x3, y3);
  let A2 = area(x1, y1, x, y, x3, y3);
  let A3 = area(x1, y1, x2, y2, x, y);
  return (A == A1 + A2 + A3);
}

let canvas = document.querySelector('canvas')

const CANVAS_SIZE = 300

canvas.width = CANVAS_SIZE
canvas.height = CANVAS_SIZE

const ctx = canvas.getContext('2d');

let arrayOfText = ['A', 'B', 'C', 'D']

ctx.beginPath();
ctx.moveTo(25, 25);
ctx.lineTo(225, 25);
ctx.lineTo(225, 225);
ctx.lineTo(25, 25);
ctx.strokeStyle = "#bb0874"
ctx.stroke()

ctx.font = `600 14px Arial`;

for (let i = 0; i < (arrayOfText.length); i++) {
  while (true) {
    let x = randomIntFromInterval(40, 180)
    let y = randomIntFromInterval(15, 160)
    if (isInside(25, 25, 225, 25, 225, 225, x, y)) {
      ctx.fillText(arrayOfText[i], x, y);
      break;
    }
  }
}
canvas {
  border: 1px solid black;
}
<body>
  <canvas></canvas>
</body>

about 4 years ago · Juan Pablo Isaza
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