0

HTML code for browse file button

<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);
} 
2
  • 5
    You've got a typo in document.getElementByID("c5");, it's getElementById Commented Feb 10, 2017 at 22:37
  • What does "not working" mean? What do you expect it to do? Commented Feb 13, 2017 at 8:42

1 Answer 1

1

There are several problems.

  • You need to use the onchange event not the click event

    <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. You need to get the filename (URL) from the element's files property

  • Change the image construction as it does not take the image URL as an argument. You set the img.src to the url then wait for the image to load.

  • The function drawImage function requires the image and at least 2 arguments that are the location to draw at.

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
    }
} 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.