古典型js屏保 南哥子

185 阅读2分钟

因为刚换岗位,感觉很浮起,中午望着屏幕发呆,时间却在抖音和今日头条上流失,

下午还有两场例会,上年纪后发现是时间推着自己跑

一直想做没做的太多了,

不管是996、还是007

心要静下来

GIF2.gif

1577326799-ddf242415243cd9.png

canvas 使用渲染文字

将canvas放置到document下

文本格式 尽可能简单 短句请大侠们谅解

var texts =	[
	'观自在菩萨',
	'行深般若波罗蜜多时',
	'照见五蕴皆空',
	'度一切苦厄',
	'舍利子',
	'色不异空 空不异色',
	'色即是空 空即是色',
	'受想行识 亦复如是',
	'舍利子是诸法空相',
	'不生不灭',
	'不垢不净',
	'不增不减',
	'是故空中无色',
	'无受想行识']

主渲染流程

function render(context) {
	context.fillStyle = "#ffffff";
	ctx.clearRect(0,0,canvas.width,canvas.height);

	var fade = tween/100.0; 
	var cc = Math.floor(fade*255);
	var fc = Math.floor(fade*100);
	var fcs = fc.toString();

	context.font      = "normal "+fcs+"px FZYTK";
	context.font.size = fc;
	context.fillStyle = "rgba(11,11,11,"+(1-fade).toString()+")";

	var pp = interp1d(pos,dpos,tween/200.0);
	fillTextVertical(context,texts[tindex],pp.x,pp.y);
	tween +=1;
}

竖排文字参考网络

function fillTextVertical(ctx,text, x, y) {
    var context = ctx;
    var canvas = context.canvas;

    
    var arrText = text.split('');
    var arrWidth = arrText.map(function (letter) {
        return context.measureText(letter).width;
    });
    
    var align = context.textAlign;
    var baseline = context.textBaseline;
    
    if (align == 'left') {
        x = x + Math.max.apply(null, arrWidth) / 2;
    } else if (align == 'right') {
        x = x - Math.max.apply(null, arrWidth) / 2;
    }
    if (baseline == 'bottom' || baseline == 'alphabetic' || baseline == 'ideographic') {
        y = y - arrWidth[0] / 2;
    } else if (baseline == 'top' || baseline == 'hanging') {
        y = y + arrWidth[0] / 2;
    }
    
    context.textAlign = 'center';
    context.textBaseline = 'middle';
    
    // 开始逐字绘制
    arrText.forEach(function (letter, index) {
        // 确定下一个字符的纵坐标位置
        var letterWidth = arrWidth[index];
        // 是否需要旋转判断
        var code = letter.charCodeAt(0);
        if (code <= 256) {
            context.translate(x, y);
            // 英文字符,旋转90°
            context.rotate(90 * Math.PI / 180);
            context.translate(-x, -y);
        } else if (index > 0 && text.charCodeAt(index - 1) < 256) {
            // y修正
            y = y + arrWidth[index - 1] / 2;
        }
        context.fillText(letter, x, y);
        // 旋转坐标系还原成初始态
        context.setTransform(1, 0, 0, 1, 0, 0);
        // 确定下一个字符的纵坐标位置
        var letterWidth = arrWidth[index];
        y = y + letterWidth;
    });
    // 水平垂直对齐方式还原
    context.textAlign = align;
    context.textBaseline = baseline;
}

文字切换

function change_text(){
	tindex = tindex<texts.length-1?tindex +=1:0 ;
	pos = {x:Math.floor(Math.random()*canvas.width/4)+130,y:Math.floor(Math.random()*canvas.height/8)+100};
	dpos = {x:pos.x+200,y:pos.y+30};
	tween = 0;
}

定时器

setInterval(function(){change_text();},1500);
setInterval(function(){render(ctx);},1000/60);

用自己喜欢的字体替换默认的仿宋和黑体,瞬间上了几个档次

康熙典藏体.png

康熙体 版权关系,请自行查找

最后附上 小抄地址