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

138
Visualizações
Positioning characters in html canvas

I have an html canvas in which I insert 5 random capital letters (A-Z). The characters have random font sizes and scale. I would like for the characters to be positioned from left to right (in the order they were created) on the canvas without overlapping and without leaving the bounds of the canvas (they do not need to be centered in the canvas). I would also like to be able to rotate the individual characters, which does not seem to work.

Here is what I have so far:

window.addEventListener('load', function() {
  getText();
  document.getElementById("reset").addEventListener("click",getText);
});

function getText() {
  var canvas = document.getElementById("myCanvas");
  var ctx = canvas.getContext("2d");
  let width = canvas.width;
  let height = canvas.height;
  ctx.save();
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  ctx.clearRect(0, 0, width, height);

  let text = "";
  let x = 20;
  let y = height / 2;
  for (var i = 0; i < 5; i++) {
    text = String.fromCharCode(Math.floor(Math.random() * 26) + 65);
    let fontSize = Math.floor(Math.random() * 15) + 20;
    ctx.font = fontSize + "px Comic Sans MS";
    ctx.fillStyle = getRandomColor();
    let scaleX = Math.floor(Math.random() * 10) / 40 + 0.8;
    let scaleY = Math.floor(Math.random() * 10) / 40 + 0.8;
    x = x + (i * width / 5) / (scaleX * 3);
    y = (height / 2) * (scaleY);
    ctx.scale(scaleX, scaleY);
    ctx.fillText(text, x, y);
  }
  ctx.restore();
}


function getRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}
<canvas id="myCanvas" width="200" height="150" style="border:1px solid #d3d3d3;">
    Your browser does not support the canvas element.
  </canvas>
  <button id="reset" type="button" name="button">Reset</button>

Thanks!

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