diff --git a/Overworld.js b/Overworld.js index 727df6e..2f455bb 100644 --- a/Overworld.js +++ b/Overworld.js @@ -76,7 +76,7 @@ class Overworld { { who: "hero", type: "walk", direction: "down" }, { who: "npc1", type: "walk", direction: "right" }, { who: "hero", type: "stand", direction: "left", time: 200 }, - { type: "textMessage", text: "Hi!" }, + { type: "textMessage", text: "Hi! Lorem ipsum" }, ]) } } \ No newline at end of file diff --git a/RevealingText.js b/RevealingText.js new file mode 100644 index 0000000..f2ecec4 --- /dev/null +++ b/RevealingText.js @@ -0,0 +1,47 @@ +class RevealingText { + constructor(config) { + this.element = config.element; + this.text = config.text; + this.speed = config.speed || 60; + + this.timeout = null; + this.isDone = false; + } + + revealOneCharacter(list) { + const next = list.splice(0,1)[0]; + next.span.classList.add("revealed"); + + if (list.length > 0) { + this.timeout = setTimeout(() => { + this.revealOneCharacter(list) + }, next.delayAfter) + } else { + this.isDone = true; + } + } + + warpToDone() { + clearTimeout(this.timeout); + this.isDone = true; + this.element.querySelectorAll("span").forEach(s => { + s.classList.add("revealed"); + }) + } + + init() { + let characters = []; + this.text.split("").forEach(character => { + let span = document.createElement("span"); + span.textContent = character; + this.element.appendChild(span); + + characters.push({ + span, + delayAfter: character === " " ? 0 : this.speed + }) + }); + + this.revealOneCharacter(characters); + } +} \ No newline at end of file diff --git a/TextMessage.js b/TextMessage.js index 2a90064..2ef4699 100644 --- a/TextMessage.js +++ b/TextMessage.js @@ -10,27 +10,38 @@ class TextMessage { this.element.classList.add("TextMessage"); this.element.innerHTML = (` -
${this.text}
+ `); + // typewriter effect + this.revealingText = new RevealingText({ + element: this.element.querySelector(".TextMessage_p"), + text: this.text + }) + this.element.querySelector("button").addEventListener("click", () => { this.done(); }); this.actionListener = new KeyPressListener("Enter", () => { - this.actionListener.unbind(); this.done(); }) } done() { - this.element.remove(); - this.onComplete(); + if (this.revealingText.isDone) { + this.element.remove(); + this.actionListener.unbind(); + this.onComplete(); + } else { + this.revealingText.warpToDone(); + } } init(container) { this.createElement(); container.appendChild(this.element); + this.revealingText.init(); } } \ No newline at end of file diff --git a/index.html b/index.html index 813ae26..d6ba1d1 100644 --- a/index.html +++ b/index.html @@ -22,6 +22,7 @@ +