cocos creator 實現打字機的效果

做爲一個萌新,我只想說我是沒有感情的粘貼工具!數組

let richText = this.viewNode.getChildByName('richText').getComponent(cc.RichText);
        const str = "<u>hello</u><color=#ff0000>Red Text,</color><br/>"+
            "<size=60>enlarge me,</size>"+
            "<br/><outline color=red width=4>A label with <i>outline,</i></outline>"+
            "<br/><b>This text will be rendered as bold,</b>"+
            "<br/><i>This text will be rendered as italic。</i>";
        this.richText(richText,str);

private richText(richTextNode,str: string = "") {
        const regex = /<.+?\/?>/g; // 匹配尖括號標籤
        const matchArr = str.match(regex);
        const specialChar = "│";
        const replaceStr = str.replace(regex, specialChar); // 標籤數組
        const textArr: string[] = replaceStr.split(specialChar); // 文字數組
        const strArr: string[] = []; // 存放處理過的文字數組
        let paraNum = 0; // 待替換參數個數
        for (let text of textArr) {
            // 非空字符替換成相似 $[0-n] 參數
            if (text !== "") {
                text = `$[${paraNum}]`;
                paraNum += 1;
            }
            strArr.push(text);
        }
        let templetStr: string = strArr.join(specialChar); // 數組轉成待替換字符串
        for (let index = 0; index < textArr.length; index++) {
            // 轉換代替換字符串以後, 刪除文字數組多餘空字符
            if (textArr[index] === "") {
                textArr.splice(index, 1);
                index = index - 1;
            }
        }
        while (templetStr.search(specialChar) !== -1) {
            // 數組轉成的字符串本來 '特殊字符' 位置都是富文本標籤的位置, 替換回標籤
            if (matchArr[0]) {
                templetStr = templetStr.replace(specialChar, matchArr[0].toString());
                matchArr.splice(0, 1);
            } else {
                templetStr = templetStr.replace(specialChar,             "");// 空字符串替換,防止死循環
                console.warn("matchArr not enough");
            }
        }
        const lastStrArr: string[] = []; // 轉換後富文本數組
        const arrayParm: string[] = new Array(paraNum).fill(""); // 替換參數數組
        for (let i = 0; i < textArr.length; i++) {
            for (const text of textArr[i]) {
                arrayParm[i] = arrayParm[i] + text;
                let replaceStr1 = templetStr;
                for (let index = 0; index < paraNum; index++) {
                    replaceStr1 = replaceStr1.replace(`$[${index}]`, arrayParm[index]);
                }
                lastStrArr.push(replaceStr1);
            }
        }
        let lastStrIndex = 0;
        const func = () => {
            if (lastStrIndex >= lastStrArr.length) {
                return;
            }
            richTextNode.string = lastStrArr[lastStrIndex];
            lastStrIndex += 1;
            setTimeout(() => {
                func();
            }, 100);
        };
        setTimeout(() => {
            func();
        }, 1000);
    }

我只是戰略性mark 打擾了~~工具

相關文章
相關標籤/搜索