Dan
Dan

Reputation: 517

wrap text within rect without overflowing it, fiddle canvas html5

I want to write text within a rectangle inside a canvas....

PROBLEM

the text overflow the rectangle...I'm thinking at incrementing the rectangle height with the text lineheight once the function wrapText() has been excecuted.....

this is a working fiddle https://jsfiddle.net/vf8gvq7m/65/ (more advanced) and for you to make an ideaof what I want to do

var canvas = document.getElementById('cv');
ctx = canvas.getContext('2d');

// core drawing function
var drawMe = function() { 
    var ImgGlasses = canvas.width = 400;
    canvas.height = 400;
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = 'blue';
	ctx.fillRect(0,0,canvas.width, canvas.height);
    ctx.fillStyle = 'red';
    ctx.fillRect(20,20,250,50);
    ctx.fillStyle = 'yellow';
    text ="hi hello how are you, i want to fill all this rectangle dinamycally. So this text doesnt overflow the rectangle";
    //ctx.fillText(text,30,30)  

    var maxWidth = 220;
    var lineHeight = 25;
    var x = 30;
    var y = 30; 
 
    wrapText(ctx, text, x, y, maxWidth, lineHeight);  
}
  
function wrapText(context, text, x, y, maxWidth, lineHeight) {
    var words = text.split(' ');
    var line = '';

    for (var n = 0; n < words.length; n++) {
        var testLine = line + words[n] + ' ';
        var metrics = context.measureText(testLine);
        var testWidth = metrics.width;
        if (testWidth > maxWidth && n > 0) {
            context.fillText(line, x, y);
            line = words[n] + ' ';
            y += lineHeight;
        } else {
            line = testLine;
        }
    }
    context.fillText(line, x, y);
}  

drawMe();
<br/>
<canvas id="cv"></canvas>

Upvotes: 0

Views: 2726

Answers (1)

Juan Caicedo
Juan Caicedo

Reputation: 1523

Define how many words do you have, after that draw rect based on length of words.

Example

const words =  text.split(' ');
const incrementFactor = 4; // it adds 4 pixels to rect for each line
const paragraphCount = words.length // Define the paragraph count
ctx.fillRect(20,20,250,paragraphCount*incrementFactor);
ctx.fillStyle = 'black';
drawWords(ctx, text, x, y, maxWidth, lineHeight,rectHeight,words)

You need to redraw canvas in each update. I suggest first define all elements to be drawn and after that draw it. Canvas does not have real-time updates, you need to redraw in each update.

working code https://jsfiddle.net/vf8gvq7m/91/

Upvotes: 1

Related Questions