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);
}
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var maxWidth = 400;
var lineHeight = 25;
var x = (canvas.width - maxWidth) / 2;
var y = 60;
var text = 'All the world \'s a stage, and all the men and women merely players. They have their exits and their entrances; And one man in his time plays many parts.';
context.font = '16pt Calibri';
context.fillStyle = '#333';
wrapText(context, text, x, y, maxWidth, lineHeight);
On Monday, 25 November 2013 at 14:45, Valentin wrote:
As far as nobody answered, I tried to implement label text wrapping by myself and reached a success. This function should be inserted into textDraw function instead of simple fillText using, and then maxWidth and lineHeight can be defined as constants as good as appropriate property and necessary defaults can be inserted in core to make text wrapping user-friendly.
Also I faced with the problem of autosizing width and height of node solving the question above. The fact is that you can wrap text by splitting it in words, but the length of word can also be longer then the node width defined during CY initialization. In that case a width of the node should be changed to the width of word plus some fixed field width.
The problem is that I don't know is it possible to change width of node during graph initialization without refreshing all the graph ele's. Is it possible? And I have another question to ask: how can I set node width after graph was initialized? I found getNodeWidth function, but can't find setNodeWidth one. Is there a way to do it or can I directly access this property from drawText and change it?