简体   繁体   English

JavaScript功能无法在HTML页面中使用

[英]JavaScript function not working in HTML page

HTML code for browse file button 浏览文件按钮的HTML代码

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

JavaScript 的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);
} 

There are several problems. 有几个问题。

  • You need to use the onchange event not the click event 您需要使用onchange事件而不是click事件

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

    You add the event listener using script rather than in line. 您使用脚本而不是直接添加事件侦听器。

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

  • The function getElementById returns an element not a string. 函数getElementById返回的元素不是字符串。 You need to get the filename (URL) from the element's files property 您需要从元素的files属性中获取文件名(URL)

  • Change the image construction as it does not take the image URL as an argument. 更改图像构造,因为它不将图像URL作为参数。 You set the img.src to the url then wait for the image to load. 您将img.src设置为url,然后等待图像加载。

  • The function drawImage function requires the image and at least 2 arguments that are the location to draw at. 函数drawImage函数需要图像和至少2个作为绘制位置的参数。

Example of changes. 变更示例。

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
    }
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM