Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
915 views
in Technique[技术] by (71.8m points)

javascript - 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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...