效果图:在线效果 click here
代码:
<!-- html代码 -->
<canvas id='c'></canvas>
//javascript代码
<script>
var ctx = document.getElementById('c').getContext('2d');
var text = document.querySelectorAll('script')[0].innerHTML;
text = text.split('/n');
ctx.height = h = text.length*20;
ctx.width = w = document.body.clientWidth;
var so = 0, //text[i]中的计数变量;
lo = 1, //text中的计数变量;
ln = 'length', fs = 'fillStyle';
ctx.textBaseline = 'top';
ctx.font = '16px monospace';
var interval = setInterval(()=>{
ctx.globalCompasiteOperation = 'source-over';
ctx.shadowBlur = 0;ctx[fs] = 'rgba(0,0,0,0.5)';
ctx.fillRect(0,0,w,h);ctx.shadowColor = 'rgba(0,255,0,0.5)';
ctx.shadowBlur = 8;ctx[fs] = '#060';
ctx.globalCompasiteOperation = 'lighter'//显示源图像+目标图像;
//打印text数组中的text[i]中的内容
text.forEach((v,i)=>{
if(i<lo){
if(i==lo){v = v.substr(0,so)};
ctx.fillText(v,50,100+16*i)
}
});
ctx.fillRect(100+ctx.measureText(text[lo].substr(0,so)).width,102+lo*16,10,14);
so++;//准备打印text[i][so]的字符;
if(so>=text[lo][ln]){lo++;so=0};//打印完text[lo]中的字符后,准备打印下一行lo+1,so归零
if(lo>=text[ln]-1){clearInterval(interval)};//打印到最后一行时跳出interval
},25)
</script>