JavaScript 文字张草

<!DOCTYPE html>
<html>  
<head>
    <title> New Document </title>
    <meta charset="utf8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0">
    <meta name="Generator" content="EditPlus">  
    <meta name="Author" content="chy龙神">  
    <meta name="Keywords" content="">  
    <meta name="Description" content="">  
    <style>
        body {
            margin: 0px;
            overflow: hidden;
            background-color: white;
        }
        canvas {
            border: 1px solid black;
        }
    </style>
</head>
<body>
    <canvas id="canvas"></canvas>  
</body>
<script>
document.body.onload = function() {
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext('2d');

    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    //待绘制的文字
    var inputStr="大话西游\n之\n爱你一万年";
    //画布水平方向的留白
    var canvasHorizontalPadding = 40;
    var doubleCanvasHorizontalPadding = canvasHorizontalPadding * 2;
    //画布宽度减去两边留白区域,得到的文字宽度阈值
    var fontWidthThreshold = canvas.width - doubleCanvasHorizontalPadding;
    //卷毛草的最大数量
    var tendrilMaxCount = 1000;
    //正在生长的卷毛草
    var tendrilArray = new Array();
    //存放文字区域的坐标
    var strPosition = [];
    /*
    时间戳(毫秒)
    (1) Date.parse(new Date())  得到秒*1000为时间戳
    (2) (new Date()).valueOf()  得到毫秒时间戳
    (3) new Date().getTime()    得到毫秒时间戳
    */
    var timestamp = new Date().getTime();

    /*
    绘制颜色为body的背景颜色(注意:这里背景一定要设置,如果不设置默认为透明,设置为白色也可以)

    element.style只能获取内嵌样式
    window.getComputedStyle(element)可以获取元素的最终样式 
    */
    ctx.fillStyle = window.getComputedStyle(document.body).backgroundColor
    console.log(window.getComputedStyle(document.body).backgroundColor);

    //字体的大小差不多就是字体四线三各的总高度
    var fontSize = 1;
    console.log("initFontSize: " + fontSize)
    var fontWidth = fontSize, lastFontWidth;
    //获取文字最适合的大小
    do {
        fontSize++;
        ctx.font = "normal " + fontSize + "px Arial";
        lastFontWidth = fontWidth;
        fontWidth = ctx.measureText(inputStr).width;
    } while(fontWidth < fontWidthThreshold);
    //还原之前一次的文字大小,并重新设置
    fontSize--;
    ctx.font = "normal " + fontSize + "px Arial";
    //ctx.fillText给出的是绘制文字的左下角坐标(注意:它并不支持换行)
    //ctx.fillText(inputStr, (canvas.width - lastFontWidth) / 2, fontSize);

    //为了给fillText添加换行效果,需要进行如下处理
    var inputArray = inputStr.split("\n");
    inputArray[inputArray.length] = "chy龍神書";

    var lastPosX = (canvas.width - lastFontWidth) / 2;
    var lastPosY = fontSize;
    for(var i=0;i<inputArray.length;i++,lastPosY+=fontSize) {
        var newWidth = ctx.measureText(inputArray[i]).width;
        if(lastPosX + newWidth > canvas.width) {
            lastPosX = (canvas.width - lastFontWidth) / 2;
        }
        ctx.fillText(inputArray[i], lastPosX, lastPosY);
        lastPosX += newWidth;

        //在文字下方绘制基线
        ctx.strokeStyle = "rgb(0,0,0)";
        ctx.beginPath();
        ctx.moveTo(0, lastPosY);
        ctx.lineTo(canvas.width, lastPosY);
        ctx.stroke();
    }
    console.log("canvas.width: " + canvas.width + ", fontSize: " + fontSize);
    //草的最大长度
    var tendrilMaxLen = fontSize/6;

    var imgData = ctx.getImageData(0,0,canvas.width,canvas.height);
    //canvas未绘制的区域默认是透明的
    for(var x=0; x<imgData.width; x++) {
        for(var y=0; y<imgData.height; y++) {
            if(getPixel(imgData,x,y)[3] > 0) {
                strPosition.push( [x,y] );
            }
        }
    }
    loop();

    function update() {
        //移除已经张到最大长度的草,维持卷毛草的数量在一个合理的范围内
        for(var i=tendrilArray.length-1; i>0; i--) {
            if(tendrilArray[i].isReachMax) {
                tendrilArray.splice(i,1);
            }
        }

        var currentTimestamp = (new Date()).valueOf();
        var timestampDiff = currentTimestamp - timestamp;
        timestamp = currentTimestamp;
        //将时间间隔按照一定比例转化为概率
        var probability = timestampDiff / 50000;
        //如果用户长时间离开后回来,时间差会变得很大
        if(probability > 0.005) {
            probability = 0.005;
        }

        // add new tendrils
        for(p in strPosition) {  
            //对于每一个点,一定的概率长出卷毛,这个概率与经过的时间间隔有关
            if(Math.random() < probability) {
                var t = new tendril();
                t.init(strPosition[p][0],strPosition[p][1]);
                tendrilArray.push ( t );
            }  
        }
        // grow actuals tendrils
        if(tendrilArray.length > 0) {
            for(t in tendrilArray) {  
                tendrilArray[t].grow(1.0, 1.0, 0.02);      
            }

        }
        //console.log(tendrilArray.length);
    }

    function render() {
        for(var i=0; i<tendrilArray.length; i++) {
            tendrilArray[i].render();
        }
    }

    function loop() {
        update();
        render();
        window.requestAnimationFrame(loop);
    }

    //获取图像指定位置的像素[r,g,b,a]
    function getPixel(imgData, x, y) {
        var offset = (x + y * imgData.width) * 4;
        var r = imgData.data[offset+0];
        var g = imgData.data[offset+1];
        var b = imgData.data[offset+2];
        var a = imgData.data[offset+3];
        return [r,g,b,a];
    }

    //卷须植物
    function tendril() {
        this.init = function(x, y) {     
            this.x = x;
            this.y = y;
            //[-PI,PI],随机的生长角度
            this.angle = Math.random() * 2 * Math.PI - Math.PI;
            //角速度
            this.v = 0;
            //当前长度
            this.length = 0;
            //是否已经达到最大长度
            this.isReachMax = false;
        };

        //grow(1.0, 1.0, 0.02);
        /*
        distance:每帧生长的长度
        curl:对角速度进行微调
        step:每帧改变的角速度,值越大卷曲度越高
        */
        this.grow = function(distance, curl, step) {  
            if(this.length < tendrilMaxLen) {
                //上次的位置
                this._x = this.x;
                this._y = this.y;
                //当前的位置
                //[0, 1, 0]
                this.x += Math.cos(this.angle) * distance;
                //[-1, 1]
                this.y += Math.sin(this.angle) * distance;
                //[-step/2, step/2]
                this.v += Math.random() * step - step / 2;
                this.v *= 0.9 + curl*0.1;
                this.angle += this.v;
                this.length++;
            } else {
                this.isReachMax = true;
            }
        };

        this.render = function() {
            if(this._x != undefined) {
                var rate = this.length/tendrilMaxLen;

                r = 8;
                //颜色由黑边绿
                g = parseInt(rate * 255);
                b = 32;

                ctx.beginPath();
                //渐渐变得透明
                ctx.strokeStyle="rgba("+r+","+g+","+b+","+(1-rate)+")";
                ctx.moveTo(this._x,this._y);
                ctx.lineTo(this.x,this.y);
                ctx.stroke();           
            }
        }
    };
}
</script>  
</html>  

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值