2017-06-18 170 views
1

我有這個修改後的矩陣Javascript代碼,我想擺脫所有重疊自己的字符串的第一次運行。有沒有人有一個想法,我可以如何管理?此外,我想多次在我的網頁上使用此代碼我需要聲明新的變量不呢?但是當我在不同的頁面上使用它時,我不需要這樣做,對吧?但是,我嘗試了兩種方法,但它沒有奏效......我很感激任何幫助。由於 你可以看到完整的代碼在這裏: https://codepen.io/eriik-re/pen/EXYOXmJavascript Bug /毛刺?

這是我的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>

+0

有什麼問題? – Carcigenicate

+0

那麼,如果你看筆,在初始化和第一次下降過程中,每個'名字'重疊,它看起來不錯,因爲你不能讀取任何東西。我的意思是下降的第一塊線。我假設這是我把所有字符串放在一起。之後,一切都很好。即使它不一定是一個錯誤,但我想盡可能刪除 – erik7

回答

1

要刪除重疊第一線的血統,可以初始化下降y偏移到畫布底部下方的行,而不是上面的行:

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支持。

+0

謝謝,它的工作。 – erik7