2013-04-25 30 views
5

Sto provando a eseguire il wrap in HTML5 Canvas ma sto lottando!Word Wrapping in HTML5 Canvas

Ho creato un oggetto TextTyper che gestirà più righe di testo avvolto da una parola.

Il problema che sto avendo è che sto ricevendo un ciclo infinito!

Ho bisogno di una soluzione che utilizzi puro JavaScript (senza jQuery) e HTML5 Canvas.

ho fatto un JSFiddle per aiutare a risolvere i miei problemi e testare diverse strategie: http://jsfiddle.net/Jamesking56/eECar/

Ecco il mio TextTyper oggetto finora:

function TextTyper(text, x, y, font, colour) 
{ 
    this.text = text || ""; 
    this.x = x || 20; 
    this.y = y || 20; 
    this.font = font || false; 
    this.colour = colour || [0, 0, 0]; 
    this.lines = 0; 

    // Calculate and draw the lines 
    this.draw = function() 
    { 
     canvas.width = canvas.width; 

     var maxWidth = (canvas.width - 40); 

     var words = this.text.split(' '); 
     var line = [words[0]]; //begin with a single word 

     for (var i = 1; i < words.length; i++) 
     { 
      while (ctx.measureText(line.join(' ')) < maxWidth && i < words.length - 1) 
      { 
       line.push(words[i++]); 
      } 

      if (i < words.length - 1) 
      { 
       //Loop ended because line became too wide 
       line.pop(); //Remove last word 
       i--; //Take one step back 
      } 
      this.lines++; 
     } 
    } 
} 

tutte le idee?

+0

Esegui il tuo codice con gli strumenti per sviluppatori e dovresti trovare il problema. –

+0

'ctx.measureText' restituisce un nuovo oggetto' TextMetrics' e non la larghezza effettiva. Probabilmente dovrai cambiarlo in 'ctx.measureText (...). Width'. Inoltre, se non svuoti mai 'line' dopo aver contato una riga, come ti aspetti di misurare la larghezza di un nuovo intervallo di parole? – Rikonator

risposta

2

Bene, questo è quello che ho usato per il mio HTML5 gioco: http://jsfiddle.net/eECar/16/

while (text.length) { 
    for(i=text.length; ctx.measureText(text.substr(0,i)).width > max_width; i--); 

    result = text.substr(0,i); 

    if (i !== text.length) 
     for(j=0; result.indexOf(" ",j) !== -1; j=result.indexOf(" ",j)+1); 

    lines.push(result.substr(0, j|| result.length)); 
    width = Math.max(width, ctx.measureText(lines[ lines.length-1 ]).width); 
    text = text.substr(lines[ lines.length-1 ].length, text.length); 
} 

Speranza che aiuta.