在rect中包装文本而不会溢出它,fiddle canvas html5

时间:2018-04-02 15:35:39

标签: javascript html5 canvas

我想在画布内的矩形内写文字......

问题

文本溢出矩形......一旦函数wrapText()被激活,我正在考虑用文本lineheight递增矩形高度.....

这是一个工作小提琴https://jsfiddle.net/vf8gvq7m/65/(更高级),让你知道我想做什么

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>

1 个答案:

答案 0 :(得分:1)

根据单词的长度,在绘制rect之后定义你有多少单词。

实施例

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)

您需要在每次更新中重绘画布。 我建议首先定义要绘制的所有元素,然后绘制它。 Canvas没有实时更新,您需要在每次更新时重绘。

工作代码https://jsfiddle.net/vf8gvq7m/91/