Javascript Bug / Glitch?

时间:2017-06-18 00:44:50

标签: javascript html5-canvas

我有这个修改过的Matrix Javascript代码,我想摆脱所有重叠的字符串的第一次运行。有没有人知道如何管理它?另外我想在我的网页上多次使用这段代码我需要声明新的变量吗?但是当我在不同的页面上使用它时,我不必这样做,对吧?但是,我试过了两个,它没有工作......我将不胜感激任何帮助。谢谢 你可以在这里看到完整的代码: https://codepen.io/eriik-re/pen/EXYOXm

这是我的js代码:

<script type="text/javascript"> var c = document.getElementById("c");
var ctx = c.getContext("2d");

document.getElementById("c").style.backgroundColor = 'rgba(255, 255, 255)';

c.height = 450;
c.width = window.innerWidth;

//chinese characters - taken from the unicode charset
var chinese = ["paylessshoes.com.au" , 
"ralphlaurenoutlet.com.au","uloadit.com.au" ,"forsterbus.com.au", 
"deanwoods.com.au" , "deanwoods.com.au" , "agelessinstantly.com.au", 
"stayhuman.com.au" , "lyndhursthotel.com.au" , "gothicweddings.com.au" , 
"growing-home.com.au" , "veglife.com.au" , 
"anagomes.com.au","soulcentralsydney.com.au" , 
 "manninghammedicalcentre.com.au" ];


var font_size = 15;
var columns = c.width/font_size; //number of columns for the rain
//an array of drops - one per column
var drops = [];
//x below is the x coordinate
//1 = y co-ordinate of the drop(same for every drop initially)
for(var x = 0; x < columns; x++)
drops[x] = 1; 

//drawing the characters
function draw()
{
//White BG for the canvas
//translucent BG to show trail
ctx.fillStyle = "rgba(255, 255, 255, 0.35)";
ctx.fillRect(0, 0, c.width, c.height);

ctx.fillStyle = "#243c84"; //blue text
ctx.font = font_size + "px arial";
//looping over drops
for(var i = 0; i < drops.length; i++)
{
    //a random chinese character to print
    var text = chinese[Math.floor(Math.random()*chinese.length)];
    //x = i*font_size, y = value of drops[i]*font_size
    ctx.fillText(text, i*font_size, drops[i]*font_size);


//sending the drop back to the top randomly after it has crossed the screen
    //adding a randomness to the reset to make the drops scattered on the Y axis
    if(drops[i]*font_size > c.height && Math.random() > 0.980)
        drops[i] = 0;

    //incrementing Y coordinate
    drops[i]++;
 }
}

setInterval(draw, 150); </script>

和HTML:  <canvas id="c"></canvas>

1 个答案:

答案 0 :(得分:1)

要删除重叠第一行的下降,可以将drop y offset初始化到画布底部下方的行,而不是顶行:

var rowOffCanvas = Math.ceil( c.height/font_size) + 1;
for(var x = 0; x < columns; x++) {
    drops[x] = rowOffCanvas;  // instead of 1
}

因此,可以轻松优化绘图功能,以便不绘制画布:

if( drops[i] < rowOffCanvas) {
    ctx.fillText(text, i*font_size, drops[i]*font_size);
}

如果您在同一页面上有多个不同的放置效果,则需要单独存储其数据值(显然和您假设的一样)。通常,这可以通过将单个拖放效果(包括画布上下文)的所有数据存储在每个效果唯一的对象中来实现。选择使用对象文字,构造函数或类声明来做到这一点取决于你,记住类声明是ES6的一部分,IE不支持。