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

247
Visualizações
How can I fix the canvas text overflowing the image?
<script>
// (B) IMAGES + CANVAS
var iBack = new Image(),

    iMark = "long text",
    canvas = document.getElementById("demo"),
    ctx = canvas.getContext("2d");

    

// (C) WATERMARK
function cmark () {
  // (C1) ADD BACKGROUND IMAGE
  canvas.width = iBack.naturalWidth;
  canvas.height = iBack.naturalHeight;
  ctx.drawImage(iBack, 100, 100, iBack.naturalWidth, iBack.naturalHeight);

  // (C2) ADD WATERMARK
  ctx.font = "bold 24px Arial";
  ctx.fillStyle = "rgba(255, 0, 0, 0.5)";
  
  ctx.fillText(iMark, 10, 100);
  ctx.fillText("width:" + ctx.measureText(iMark).width, 100, 50);
  
  
  
    

  /* (C3) DOWNLOAD (IF YOU WANT)
  let anchor = document.createElement("a");
  anchor.href = canvas.toDataURL("image/png");
  anchor.download = "marked.png";
  anchor.click();
  anchor.remove();*/
}

// (D) GO - PROCEED ONLY WHEN IMAGES ARE LOADED
iBack.onload = cmark;
iBack.src = "image.jpg";
</script>

When I write long text, it takes it out of the picture. I don't want it to spill out of the picture. How can I fix the canvas text overflowing the image? Can you help me?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can draw only one line of text at a time with filltext(), so you need to split you text into several parts when it's too long. You can use measureText(iMark)to measure the length of you text, :

if (measureText(iMark)>100) {
    let temp1 = iMark.slice(0,iMark.length/2);
    let temp2 = iMark.slice(iMark.length/2,iMark.length);
    ctx.fillText(temp1, 10, 100);
    ctx.fillText(temp1, 10, 200);
}
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