TheaterJS是一款模拟打字机效果的js打字机效果插件。
使用方法
可以使用下面的js代码来调用TheaterJS制作打字机效果:
var theater = new TheaterJS(); theater .describe( "Vader" , .8, "#vader" ) .describe( "Luke" , .6, "#luke" ); theater .write( "Vader:Luke." , 600) .write( "Luke:What?" , 400) .write( "Vader:I am..." , 400, " your father." ); theater .on( "say:start, erase:start" , function () { // add blinking caret }) .on( "say:end, erase:end" , function () { // remove blinking caret }) .on( "*" , function () { // do something }); |
多重角色
使用TheaterJS,你可以建立多个角色,每个角色都有自己的“经验”,它们使用这些“经验”可以互相“交谈”。
theater.describe( "Vader" , .8, "#vader" ); |
上面的代码描述了一个新的角色,名字叫“Vader”,它的“经验”值为0.8(必须是0-1之间),它的voice是“#vader”。voice将用于打印的文字,Vader是一个html元素。
voice可以是两种类型:
- 一个HTML元素(或一个CSS选择器),元素的
innerHTML
将被用于设置voice。 - 用4个参数调用的函数:
- newValue:新的speech值。
- newChar:新的打印字符。
- prevChar:前一个字符。
- speech:所有的speech。
注意:当TheaterJS调用了这些函数,上下文this
被设置为当前对象。
创作剧本
TheaterJS实际上是在创建一个剧本。
theater .write( "Vader:I am your father." ) .write( " For real...." ) .write(-1) .write(600) .write( function () { /* do something */ }); |
注意:write
方法接收不定数量的参数。
theater .write( "Vader:Hello!" ) .write( "How are you doing?" ); |
等效于
theater.write( "Vader:Hello!" , "How are you doing?" ); |
设置 actor 和 speech
theater.write( "Vader:I am your father." ); |
write
方法的参数是以角色的名字为前缀的字符串。它实际上添加了三个场景:
场景名称 | 描述 |
actor | Set the current speaking actor to the passed one. |
erase | Erase the current speech value. |
actor | Type the speech. |
场景对象
theater .write( "Vader:I am your father." ) .write( " For real...." ) .write(-1) .write(600) .write( function () { /* do something */ }); |
它等效于
theater .write({ name: "actor" , args: [ "Vader" ] }) .write({ name: "erase" , args: [] }) .write({ name: "say" , args: [ "I am your father." ] }) .write({ name: "say" , args: [ " For real...." ] }) .write({ name: "erase" , args: [-1] }) .write({ name: "wait" , args: [600] }) .write({ name: "call" , args: [ function () { /* do something */ }] }); |
事件
TheaterJS有一些内置的事件。
theater .on( "say:start" , function (event, args...) { console.log( "a say scene started" ); }) .on( "say:end" , function (event, args...) { console.log( "a say scene ended" ); }); |
在 : 之前的值是事件的作用域,其它部分是事件本身。要添加一个事件监听,可以使用逗号隔开它们。
theater .on( "say:start, erase:start" , function (event) { // add blinking caret }) .on( "say:end, erase:end" , function () { // remove blinking caret }); |
如果你想监听所有的事件,使用theater.on("*", function (event, realEvent, args...) {});
方法。
公共方法
theater .emit( "scope" , "event" , [ "your" , "arguments" , "go" , "here" ]) .emit( "customEvent" , [ "you might not need the event part" ]); |
emit
方法接收三个参数:第一个是作用域,第二个是事件,第三个是参数。
更多详细信息请参考:https://github.com/Zhouzi/TheaterJS