【Canvas技巧】文字渐隐渐显的实现

【关键点】

描绘文字前控制其alpha值,这个值能控制文字的透明度。

在本作中,alpha值是三角函数加绝对值函数实现的。

【图示】

【代码】

<!DOCTYPE html>
<html lang="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<head>
     <title>文字渐隐效果</title>
     </head>

     <body onload="draw()">
        <canvas id="myCanvas" width="100px" height="100px" style="border:0px dashed black;">
            出现文字表示您的浏览器不支持HTML5
        </canvas>
     </body>
</html>
<script type="text/javascript">
<!--
/*****************************************************************
* 将全体代码(从<!DOCTYPE到script>)拷贝下来,粘贴到文本编辑器中,
* 另存为.html文件,再用chrome浏览器打开,就能看到实现效果。
******************************************************************/

// 常量画布宽
const Width=400;

// 常量画布高
const Height=400;

// 绘图上下文
var context;

// 舞台对象
var stage;

// 肇始函数
function draw(){
    // Canvas
    var canvas=document.getElementById('myCanvas');    
    canvas.width=Width;
    canvas.height=Height;    
    context=canvas.getContext('2d');    
    
    // 准备
    stage=new Stage();    
    stage.init();

    // 开幕
    animate();
};

// 循环播放动画
function animate(){    
    stage.update();
    stage.paintBg(context);
    stage.paintFg(context);     

    if(true){
        // 延时执行
        const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms)); 
        delay(90).then(() => {
            window.requestAnimationFrame(animate);
        });        
    }
}

// 舞台类
function Stage(){
    this.alpha=0;
    
    // 初始化粒子
    this.init=function(){

    }

    // 更新粒子的位置
    this.update=function(){
        this.alpha+=0.1;
        if(this.alpha>=10){
            this.alpha=0;
        }
    };

    //  画背景
    this.paintBg=function(ctx){
        ctx.fillStyle="black"; 
        ctx.fillRect(0,0,Width,Height);

        // 作者标识
        ctx.fillStyle="yellow";
        ctx.font="6px Arial";
        ctx.fillText("            by:逆火",Width-90,Height-20);
    };

    // 画前景
    this.paintFg=function(ctx){
        ctx.font="28px consolas";
        ctx.fillStyle = "rgba(249, 249, 0, "+Math.abs(Math.sin(this.alpha))+")";  // 关键所在
        ctx.fillText("文字渐隐渐显",110,220);
    };
}

/*----------------------------------
魔鬼的广告
你若俯伏拜我,我就把一国与这国的荣华赐你
你若俯伏拜我,我就把一省与这省的荣华赐你
你若俯伏拜我,我就把一县与这县的荣华赐你
----------------------------------*/ 

//--> </script>

 

END

posted @ 2013-09-28 20:33  逆火狂飙  阅读(242)  评论(0编辑  收藏  举报
生当作人杰 死亦为鬼雄 至今思项羽 不肯过江东