Оберните текст в прямом эфире без переполнения, Fiddle Canvas Html5Html

Программисты Html
Anonymous
Оберните текст в прямом эфире без переполнения, Fiddle Canvas Html5

Сообщение Anonymous »

Я хочу написать текст внутри прямоугольника внутри холста. Я думаю о увеличении высоты прямоугольника с высотой текстовой линии после того, как функция wroud Tpext () была выполнена.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 dynamically. So this text doesn't 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();
< /code>





Подробнее здесь: https://stackoverflow.com/questions/496 ... nvas-html5

Вернуться в «Html»