Как разбить строку на x равных строк в javascript (с выравниванием текста)

Я отчаянно пытаюсь разбить случайную строку на равные части, чтобы я мог оформить каждую из них отдельно. Моя цель — создать искаженный эффект для моего текста, но сохранить текст по ширине и без разделенных слов.

Как вы можете видеть на этом примере, я пытался сделать что-то подобное, но результат действительно дрянной.:

http://vps10937.ovh.net/hyphenator/WorkingExample1.html (Платон 2)

Вот мой код:

jQuery(document).ready(function() {
    jQuery('p.platon2').each(function(index) {
    lengthTotal = jQuery(this).text().length
    var string = jQuery(this).text();
    string = jQuery.trim(string);
    var length = 56;
    var trimmedString = string.substring(0, length);
    jQuery(this).text('');
    lengthTotalPrev = 0;
    j=0;
    z=0
      for (i=length; i<lengthTotal;  i=i+length){
        j++;
        z=z+5;
        rowString = string.substring(lengthTotalPrev, i);
        jQuery(this).append('<span id="row'+j+'" class="rows" style="position:relative;left:-'+z+'px;">'+rowString+'</span>');
        lengthTotalPrev = i;
      }
    });
});

Теперь я пытаюсь использовать плагин hyphenator.js, чтобы правильно разделить мой текст и получить равные линии.

http://vps10937.ovh.net/hyphenator/WorkingExample1.html ( Платон 1)

Вызвать плагин очень просто:

Hyphenator.config({
    displaytogglebox : true,
    minwordlength : 4
});
Hyphenator.run();

Результат красивый, но с этим я не могу применять CSS к каждой строке, чтобы мой текст искажался. Я изучил файл hyphenator.js (нажмите здесь, чтобы увидеть исходный код) сверху вниз. , но не нашел ничего, чтобы разбить текст на строки..


ИЗМЕНИТЬ


Я изменил плагин, найденный на github. Благодаря этому я теперь могу сделать что-то близкое к желаемому результату. Но есть еще некоторые проблемы.

http://vps10937.ovh.net/hyphenator/WorkingExample1.html (Платон 3)

1) Скрипт работает очень медленно. Можно ли кэшировать результат?

2) Текст больше не выравнивается, поэтому строки не совсем равны...

3) Работает только в Firefox!!

http://vps10937.ovh.net/hyphenator/jquery.truncatelines.js

$.fn.truncateLines = function(options) {
options = $.extend($.fn.truncateLines.defaults, options);

return this.each(function(index, container) {

    container = $(container);
    var containerLineHeight = Math.ceil(parseFloat(container.css('line-height')));

    var maxHeightFixed = containerLineHeight;
    //var maxHeight = options.lines * containerLineHeight;

    var truncated = false;
    var truncatedText = $.trim(container.text());
    //var overflowRatio = container.height() / maxHeight;

    var oldTruncatedText; // verify that the text has been truncated, otherwise you'll get an endless loop
    var oldContainerHeight;
    textArray= new Array();

    jQuery(document.body).append('<p class="paragraphProvisory1" style="display: none;"></p>');
    jQuery(document.body).append('<p class="paragraphProvisory2" style="display: none;"></p>');

    while (container.height() > 0 && oldTruncatedText != truncatedText) {
        if(oldContainerHeight!=container.height()){


            truncatedTextTest = truncatedText;
            jQuery('.paragraphProvisory1').text(truncatedTextTest);

            //11nd line 
            if(container.height()==containerLineHeight*11){
                createLine(10);
            }
            //10nd line 
            if(container.height()==containerLineHeight*10){
                createLine(9);
            }
            //9nd line  
            if(container.height()==containerLineHeight*9){
                createLine(8);
            }
            //8nd line  
            if(container.height()==containerLineHeight*8){
                createLine(7);
            }
            //7nd line  
            if(container.height()==containerLineHeight*7){
                createLine(6);
            }
            //6nd line  
            if(container.height()==containerLineHeight*6){
                createLine(5);
            }
            //5nd line  
            if(container.height()==containerLineHeight*5){
                createLine(4);
            }
            //4nd line  
            if(container.height()==containerLineHeight*4){
                createLine(3);
            }
            //3nd line  
            if(container.height()==containerLineHeight*3){
                createLine(2);
            }
            //2nd line  
            if(container.height()==containerLineHeight*2){
                createLine(1);
            }
            //1st line      
            if(container.height()==containerLineHeight*1){
                textArray[0]= "<div class='line1'>"+truncatedTextTest+"</div>";     
            }

        }

        oldTruncatedText = truncatedText;
        oldContainerHeight = container.height()
        truncatedText = truncatedText.replace(/\s.[^\s]*\s?$/, ''); // remove last word
        container.text(truncatedText);

    }

    jQuery('.platon3').text('');
    jQuery.each(textArray, function(i) {
     jQuery('.platon3').append(textArray[i]);
});

});
};
function createLine(rowNumber){
    var oldTruncatedTextTest;
    var row = 0;
    positionLeft = rowNumber * 10;
    rowNumber++;
    jQuery('.paragraphProvisory2').text(truncatedTextTest);
        containerTest = $('.paragraphProvisory2');
        while (containerTest.height() > 20 && oldTruncatedTextTest != truncatedTextTest) {
            row++;
            oldTruncatedTextTest = truncatedTextTest;
            truncatedTextTest = truncatedTextTest.substr(truncatedTextTest.indexOf(" ") + 1);
            jQuery('.paragraphProvisory2').text(truncatedTextTest);
            if(containerTest.height()==20){
                textArray[rowNumber]= "<div class='line"+rowNumber+"' style='position: relative; left: -"+positionLeft+"px;'>"+truncatedTextTest+"</div>";
            }
        }
};

person Kr1    schedule 03.10.2012    source источник
comment
Почему бы не опубликовать код, который вы создали до сих пор. Так что другие могут помочь вам построить на этом коде.   -  person cube    schedule 03.10.2012
comment
Как вы и хотели, я выложил все, что у меня есть!   -  person Kr1    schedule 03.10.2012
comment
Это супер интригующе! Я предполагаю, что вы так и не нашли кросс-браузерное решение, которым вы довольны? Я рассматривал возможность разделения контента на горизонтальные равные столбцы или даже блоки, чтобы эмулировать множество переходов слайдера мультимедиа. Переход на холст, вероятно, будет проще (хотя я не использовал холст достаточно, чтобы действительно знать)   -  person David Hobs    schedule 29.10.2012


Ответы (2)


Это не совсем то, что вам нужно, но вы можете перекосить весь текстовый контейнер, чтобы он подходил с помощью css3:

.platon {
  transform: skew(160deg,0deg);
  -ms-transform: skew(160deg,0deg);
  -moz-transform: skew(160deg,0deg);
  -webkit-transform: skew(160deg,0deg);
  -o-transform: skew(160deg,0deg);
  width: 367px;
}
person Hank    schedule 03.10.2012
comment
Спасибо за это, но я уже знаю это правило css. Проблема в совместимости с Internet Explorer. Мне нужно, чтобы он был абсолютно функциональным в каждом браузере. vps10937.ovh.net/hyphenator/WorkingExample1.html - person Kr1; 04.10.2012

Если я вас правильно понимаю, вы хотите применить свой собственный CSS к каждой строке перенесенной через дефис... Таким образом, вы должны определить свой собственный classname следующим образом:

        Hyphenator.config({                
classname : 'yourclass',             

 })
person cube    schedule 03.10.2012
comment
Здравствуйте, это не совсем то, что мне нужно. Я хочу что-то вроде моего примера Платон 3 vps10937.ovh.net/hyphenator/WorkingExample1.html .Но строки не совсем равны - person Kr1; 04.10.2012