Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

248
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!