2017-02-10 96 views
0

HTML代碼的瀏覽文件按鈕JavaScript函數在HTML頁面無法正常工作

<input type="file" multiple="false" accept="image/*" id="filein" onclick="filo()"> 

的JavaScript

function filo(){ 
    var canin= document.getElementByID("c5"); 
    var imgin = document.getElementById("filein"); 
    var xct = canin.getContext("2d"); 
    var img = new Image(filein); 
    xct.drawImage(canin); 
} 
+5

你必須在'的document.getElementById( 「C5」),一個錯字;',它是'getElementById' – topheman

+0

什麼是 「不工作」 是什麼意思?你期望它做什麼? – halfer

回答

1

有幾個問題。

  • 您需要使用onchange事件不是click事件

    <input type="file" multiple="false" accept="image/*" id="filein">

    您使用腳本添加事件偵聽器,而不是線。

    <script> // this script must be place after the element filein or use an onload event. filein.onchange = filo(); </script>

  • getElementById不返回元素的字符串的函數。您需要從元素的files屬性中獲取文件名(URL)

  • 更改圖像構造,因爲它不會將圖像URL作爲參數。您將img.src設置爲url,然後等待圖像加載。

  • 函數drawImage函數要求圖像和至少2個參數是要繪製的位置。

變化的示例。

function filo() { 
    // Get the filename of the input element 
    var imgin = document.getElementById("filein").files[0]; // <<Get the file URL 

    // Typo its getElementById not getElementByID 
    var canin= document.getElementById("c5"); 
    var xct = canin.getContext("2d"); 

    // Image does not take a URL via the constructor 
    var img = new Image(); 

    // set the URK here 
    var img.src = imgin; 

    // you need to wait for the image to load then you can draw it 
    img.onload = function() { 

     // drawImage function requires the image and at least 2 arguments 
     // that are the location to draw at  
     xct.drawImage(this, 0, 0); // this is the image in the onload event 
    } 
}