2013-10-11 70 views
0

我有一個似乎很簡單的問題,但我似乎無法找到關於我的問題的任何資源。我想要做的是將36個圖像從計算機內的文件夾存儲到使用Javascript的數組中。以下是相關代碼片段的簡短版本。Javascript;從保存文件夾圖像陣列

<!doctype html> 
    <head> 
     <style> 
     div#GameBoard { 
     position: absolute; 
     top: 66px; 
     left: 53px; 
     display: block; 
     margin: 10px; 
     padding: 10px; 
     border: ridge #7CFC00 15px; 
     width: 1007px; 
     height: 698px; 
     } 

     div#Flipper { 
     display: block; 
     position: relative; 
     background-color: #000; 
     }  
    <style> 

    <script lang="javascript"> 
     var ImgArray = [[11-16][21-26][31-36][41-46][51-56][61-66]]; 
     // pseudocode, the first digit is for row, second digit is for column number. 
     //I've named the pictures accordingly within the folder as 11.png,12.png,21.png, 
     //and within the array //as well. 

     function OnClickCard(path) 
     { 
     path || path ='C:\Users\Jamal\Desktop\codefolder\memorygame\gameimages' 

     document.getElementById("Flipper").img.src = ImgArray.splice(Math.floor(Math.random() * ImgArray.length)[ImgArray]; 
     } 
    </script> 
    <body> 
    <div id="GameBoard"> 
     <div class="Tile" id="Flipper"> 
      <img name ="11" src="blue-glass-tile.png" onclick="OnClickCard()"/> 
     </div> 

    </body> 
    </head> 
</html> 

所以,我希望它做的是保存裏面的圖片36「C:\用戶\賈馬爾\桌面\ codefolder \ memorygame \ gameimages」內的陣列,並拼接0-35隨機指數改變到圖像源在div,除去該索引使得它不會被使用兩次。

究竟發生了什麼..沒什麼。我一直在運行在Firefox的開發者控制檯,並清除了所有的錯誤,但硬是沒有任何反應。我不知道如何運行控制檯日誌來檢測圖像是否已加載的錯誤。我很茫然,甚至已經跳到了邏輯。在這個時候,我迫切需要完成隨機程序,這使我瘋狂。我非常感謝您可能有的任何輸入。

回答

0

首先,你的代碼示例中有幾個錯誤。 #Gameboard沒有結束<div>標籤,並在使用path

其次,運行一個控制檯日誌一樣簡單

console.log("logging statement"); 

內JavaScript代碼。

現在你真正的問題。您的問題的原因是瀏覽器與您的計算機的底層操作和文件系統有限的交互。當您使用

<input type = 'file' id = file_input' /> 

它,使連接的瀏覽器和您選擇的文件上傳

取決於你有瀏覽器的類型及其與File API的兼容性,可以使用輸入標籤並將Javascript函數綁定到提交事件以執行您想要的操作。

但是,將圖像放入服務器會更好也更容易,然後您可以通過瀏覽器中的URL訪問該圖像。如果您打算爲自己的機器做到這一點,只需安裝一個的Apache/MySQL的/ PHP堆棧和本地主機文件夾中保存數據。

0

下面以一個簡單的方法,它假定你有興趣在圖像src路徑,而不是blob內容的圖像。我希望它能指出你正確的方向。

基本上做到如下:

  • 添加您的圖像在你的HTML頁面。
  • 讓你的所有圖像在JS中的陣列document.images
  • 循環圖像陣列以便僅查找src路徑。
  • 使用data陣列根據自己的喜好。

var images = document.images, 
 
    data = []; 
 
for (var i = 0, len = images.length; i < len; i++) { 
 
    data.push(images[i].src); 
 
    console.log(data[i]); 
 
} 
 
// do whatever you want with array data
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150"> 
 

 
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=150%C3%9710&w=150&h=200">