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

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

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 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