2010-05-14 5 views
2

Как я могу охарактеризовать отдельные символы текста на странице в HTML5. Как этот пример во вспышке. http://www.greensock.com/splittextfield/Как анимировать текст символов с помощью html5

+0

Retagged. Вопрос, похоже, не о вспышке. Почему вы ограничиваете себя HTML5? – Eric

+1

@ Эрик: Потому что в последнее время все крутые дети говорят об этом. –

+0

У вас нет. CSS и javascript делают это, а не HTML. – Rob

ответ

3

Вы бы обернуть каждый символ в <span> затем перенести этот срок с помощью CSS position/top/left.

Вы не смогли полностью воспроизвести то, что сделал пример Flash, потому что этот пример использует эффект размытия. CSS не может этого сделать; SVG мог, и IE нестандартный filter мог, но это означало бы полную ветвь кода.

Вы можете изменить размер каждой буквы, установив font-size, но для такого эффекта сдвига/поворота на примере вам нужно будет использовать CSS transform. Это еще не стандартизировано, и есть отверстия в поддержке браузера.

Вот концепция корректуры из-я просто изрубил в основном для Firefox (извините за длинами коды):

<p id="effect">I've got a lovely bunch of coconuts.</p> 
<button id="animate">Animate</button> 


// Add ECMA262-5 method binding if not supported natively 
// 
if (!('bind' in Function.prototype)) { 
    Function.prototype.bind= function(owner) { 
     var that= this; 
     if (arguments.length<=1) { 
      return function() { 
       return that.apply(owner, arguments); 
      }; 
     } else { 
      var args= Array.prototype.slice.call(arguments, 1); 
      return function() { 
       return that.apply(owner, arguments.length===0? args : args.concat(Array.prototype.slice.call(arguments))); 
      }; 
     } 
    }; 
} 

// Lightweight class/instance system 
// 
Function.prototype.makeSubclass= function() { 
    function Class() { 
     if (!(this instanceof Class)) 
      throw 'Constructor function requires new operator'; 
     if ('_init' in this) 
      this._init.apply(this, arguments); 
    } 
    if (this!==Object) { 
     Function.prototype.makeSubclass.nonconstructor.prototype= this.prototype; 
     Class.prototype= new Function.prototype.makeSubclass.nonconstructor(); 
    } 
    return Class; 
}; 
Function.prototype.makeSubclass.nonconstructor= function() {}; 

// Abstract base for animated linear sliding switch between 0 and 1 
// 
var Animation= Object.makeSubclass(); 
Animation.prototype._init= function(period, initial) { 
    this.period= period; 
    this.interval= null; 
    this.aim= initial || 0; 
    this.t= 0; 
}; 
Animation.prototype.set= function(aim) { 
    if (aim===this.aim) 
     return; 
    this.aim= aim; 
    var now= new Date().getTime(); 
    if (this.interval===null) { 
     this.t= now; 
     this.interval= window.setInterval(this.update.bind(this), 32); 
    } else { 
     this.t= now-this.t-this.period+now 
     this.update(); 
    } 
}; 
Animation.prototype.toggle= function() { 
    this.set(this.aim===0? 1 : 0); 
}; 
Animation.prototype.update= function() { 
    var now= new Date().getTime(); 
    var x= Math.min((now-this.t)/this.period, 1); 
    this.show(this.aim===0? 1-x : x); 
    if (x===1) { 
     window.clearInterval(this.interval); 
     this.interval= null; 
    } 
}; 
Animation.prototype.show= function(d) {}; 

// Animation that spins each character in a text node apart 
// 
var ExplodeAnimation= Animation.makeSubclass(); 
ExplodeAnimation.prototype._init= function(node, period) { 
    Animation.prototype._init.call(this, period, 0); 
    this.spans= []; 

    // Wrap each character in a <span> 
    // 
    for (var i= 0; i<node.data.length; i++) { 
     var span= document.createElement('span'); 
     span.style.position= 'relative'; 
     span.appendChild(document.createTextNode(node.data.charAt(i))); 
     node.parentNode.insertBefore(span, node); 
     this.spans.push(span); 
    } 

    // Make up random positions and speeds for each character. 
    // Possibly this should be re-randomised on each toggle? 
    // 
    this.randomness= []; 
    for (var i= this.spans.length; i-->0;) 
     this.randomness.push({ 
      dx: Math.random()*200-100, dy: Math.random()*200-150, 
      sx: Math.random()*1.5, sy: Math.random()*1.5, 
      dr: Math.random()*240-120, og: Math.random()+0.5 
     }); 

    node.parentNode.removeChild(node); 
}; 
ExplodeAnimation.prototype.show= function(d) { 
    for (var i= this.spans.length; i-->0;) { 
     var style= this.spans[i].style; 
     var r= this.randomness[i]; 

     style.left= d*r.dx+'px'; 
     style.top= d*r.dy+'px'; 
     var transform= 'rotate('+Math.floor(d*r.dr)+'deg) scale('+(d*r.sx+1-d)+', '+(d*r.sy+1-d)+')'; 
     if ('transform' in style) 
      style.transform= transform; 
     else if ('MozTransform' in style) 
      style.MozTransform= transform; 

     var o= 1-Math.pow(d, r.og); 
     if ('opacity' in style) 
      style.opacity= o+''; 
     else if ('filter' in style) 
      style.filter= 'opacity(alpha='+Math.ceil(o*100)+')'; 
    } 
}; 


var animation= new ExplodeAnimation(document.getElementById('effect').firstChild, 1000); 
document.getElementById('animate').onclick= animation.toggle.bind(animation); 

Это может быть улучшен путем добавления гравитации и лучшее моделирования 3D-пространства currently- полностью-случайные преобразования, а также лучшую поддержку браузера для масштабирования/вращения в браузерах, отличных от Firefox.

(IE имеет свой собственный нестандартный CSS transform filters можно было бы поддержать, Webkit и Opera имеют webkitTransform и oTransform стили, но они отказываются от преобразования относительного позиционирования встроенных пролеты, так что вы должны были бы абсолютной позиции каждого характер, что означало бы чтение всех их нормальных позиций для использования в качестве базовой линии. Мне было скучно на этом этапе.)

+1

хотел бы видеть это в действии! PS: вы можете подделать размытие с помощью «text-shadow: 0 0 5px samecolorasfont» – meo

+1

... в сочетании с 'color: rgba (0,0,0,0)', чтобы остановить сам текст. Умная! Но я ухожу. – bobince

+1

Да, хорошая идея, я попробовал ее с непрозрачностью, но с rgba это выглядело бы намного лучше! http://jsfiddle.net/GqTam/1/ – meo

Смежные вопросы