Halaman

Minggu, 12 Januari 2014

wrapText - HTML5 - javascript

function wrapText(context, text, x, y, maxWidth, lineHeight) {
//manage carriage return
 text = text.replace(/(\r\n|\n\r|\r|\n)/g, "\n");
//manage tabulation
text = text.replace(/(\t)/g, " "); // anything you want
//array of lines
var sections = text.split("\n");

for (s = 0, len = sections.length; s < len; s++) {
var words = sections[s].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) {
context.fillText(line, x, y);
line = words[n] + ' ';
y += lineHeight;
} else {
line = testLine;
}
}
context.fillText(line, x, y);

//new line for new section of the text
y += lineHeight;
}
};


Cara memanggil:
var maxWidth = 300; // lebar area teks
var lineHeight = 20; // tinggi teks
var str = 'teks panjang  yang akan dijadikan beberapa baris'
wrapText(context, str, 0, 0, maxWidth, lineHeight);


sumber:
http://stackoverflow.com/questions/15582937/vertical-align-text-on-html-5-canvas

Tidak ada komentar:

Posting Komentar