zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    电脑知识
    编译器错误信息: CS0433: 类型“ASP.global_asax”同时存在于“c:/WINDOWS/Microsoft.NET/Framework/v2.0.50727...的解决方法
    windows平台下的oracle ORA-01031的解决方法
    .NET下使用HTTP请求的正确姿势
    EasyUI Datagrid 分页
    Js 运算符(加减乘除)
    Navicat 运行 Oracle 存储过程示例
    oracle数据库忘记sys(或system)账户密码
    SQL Server 死锁问题
    C# 给某个方法设定执行超时时间
  • 原文地址:https://www.cnblogs.com/niubenbit/p/3711735.html
Copyright © 2011-2022 走看看