• canvas打字效果


    运用fillText,写的打字效果。

    唯一麻烦的地方是,换行问题,

    我是把字符串转化为数组,数组一个单位完成,就换行,继续下一个单位。

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>canvas</title>
    <style type="text/css">
    canvas { border: 1px solid black; }
    #change{width:200px; line-height:30px; color:#fff; text-align:center; background:blue;}
    </style>
    <script type="text/javascript" charset="utf-8">
    var text = "东临碣石,以观沧海。|水何澹澹,山岛竦峙。|树木丛生,百草丰茂。|秋风萧瑟,洪波涌起。|日月之行,若出其中。|星汉灿烂,若出其里。|幸甚至哉,歌以咏志。";
    var arr = text.split("|");
    var line = 0;
    var timer = 0;
    var i = 0;
    var newText = "";
    
    function Typing(id) {
        var canvas = document.getElementById(id);
        if (canvas == null) {
            return false;
        }
        scrollit();
    }
    
    function scrollit() {
        newText = arr[line].slice(0, i++) + "_";
        var context = canvas.getContext("2d");
        // 擦除文字
        context.clearRect(0, 20 + line * 30, 600, 20 + 30 * (line + 1));
        var gradient = context.createLinearGradient(0, 0, 200, 0);
        gradient.addColorStop("0", "magenta");
        gradient.addColorStop("0.5", "blue");
        gradient.addColorStop("1.0", "red");
        context.fillStyle = gradient;
        context.font = "20px Verdana";
        context.textBaseline = "hanging";
    
        if (i > arr[line].length) {
            newText = arr[line].slice(0, arr[line].length);
            context.fillText(newText, 30, 20 + 30 * line);
            // 换行
            i = 0;
            line++;
            if (line < arr.length) {
                clearTimeout(timer);
                scrollit();
            };
        } else {
            context.fillText(newText, 30, 20 + 30 * line);
            timer = setTimeout(scrollit, 200);
        }
    }
    
    window.onload = function() {
        Typing("canvas");
    }    
    </script>
    </head>
    
    <body>
    <canvas id="canvas" width="600" height="400"></canvas>
    <img id="newImg" src="" alt="" widt="100" height="100">
    <div id="demo">hh</div>
    </html>
  • 相关阅读:
    leetcode@ [68] Text Justification (String Manipulation)
    leetcode@ [205] Isomorphic Strings
    leetcode@ [274/275] H-Index & H-Index II (Binary Search & Array)
    leetcode@ [174] Dungeon Game (Dynamic Programming)
    Java 开发@ JDBC链接SQLServer2012
    leetcode@ [97] Interleaving Strings
    leetcode@ [131/132] Palindrome Partitioning & Palindrome Partitioning II
    leetcode@ [263/264] Ugly Numbers & Ugly Number II
    py-day1-1 python的基本运算符和语句
    py-day1 pycharm 的安装 以及部分设置
  • 原文地址:https://www.cnblogs.com/niubenbit/p/3711735.html
Copyright © 2020-2023  润新知