I have a small hobby project in which I try to build a matrix rain: .
See demo http://www.audenaerde.org/matrix.html这里。或这个JSFiddle https://jsfiddle.net/5o9uakkc/
我的问题是:如何才能提高效率,因为我可以看到当我添加很多列时它会变慢。
我已经将它实现为渲染很多absolute
定位div
是动画的。
这是我的CSS:
div
{
position:absolute;
width:1em;
display:inline-block;
color: black;
animation-name: example;
animation-duration: 2s;
text-shadow: none;
}
@keyframes example
{
0% {color: white; text-shadow: -1px 1px 8px white;}
15% {color: #5f5 ; text-shadow: -1px 1px 8px #5f5 ;}
100% {color: black; text-shadow: none;}
}
在 javascript 中,我为每个设置了一些自定义样式div
,我在其中改变了一些设置,例如字体大小、动画速度等。
JS的主要部分:
var textStrip = ['诶', '比', '西', '迪', '伊', '吉', '艾', '杰', '开', '哦', '屁', '提', '维'];
var matrixcol = function()
{
var top = Math.floor(Math.random() * $(window).height() * 0.5);
var size = 10 + Math.floor(Math.random()*10);
var col = Math.floor(Math.random() * $(window).width() - size);
var ms = 500 + Math.floor(Math.random()*1500);
var timer;
var aap = function()
{
var randomNumber = Math.floor(Math.random()*textStrip.length);
var newelem = $("<div style='font-size:"+ size+ "px;top:"+top+"px; left:"+col+"px;animation-duration:"+ 2*ms + "ms'>" + textStrip[randomNumber] + "</div>" );
$('body').append(newelem);
top+=size;
setTimeout( function() {newelem.remove();}, (1.6*ms)-(ms/40));
if (top>$(window).height()-size)
{
size = 10 + Math.floor(Math.random()*10);
top=0; Math.floor(Math.random() * $(window).height() * 0.5);
col = Math.floor(Math.random() * $(window).width() -size);
ms = 500 + Math.floor(Math.random()*1500);
clearInterval(timer);
timer = setInterval(aap, ms/40);
}
}
timer = setInterval(aap, ms/40);
}
$( document ).ready(function() {
var i;
for (i = 0; i < 25; i++) {
matrixcol();
}
我尝试使用 chrome 分析,它显示了警告:
长帧时间表明卡顿和渲染效果不佳
表现。
提供的链接提供了一些见解;然而,据我所知,我没有进行太多布局。
tl;dr它很慢。什么是好的性能优化?