Trying to load canvas image from file directory

I found this jsfiddle http://jsfiddle.net/t7mv6/86/ which works exactly as I need it to. Searched for examples and explored several online html5 tutorials. I'm trying to load multiple images, selected from many in a directory, into one html5 canvas. I wrote this try using a jsfiddle:

<!DOCTYPE html>
<html>
  <HEAD>
 <script type="text/javascript">
var input = document.getElementById('input');

input.addEventListener('click', handleFiles);
var i=0;
function handleFiles(e) {alert("here");

    var ctx = document.getElementById('canvas').getContext('2d');

    var img = new Image;
    alert("hello");
    img.src = URL.createObjectURL(e.target.files[0]);
    img.onload = function() {
        ctx.drawImage(img, 20,20);
        alert('the image is drawn');

    }
}
  </script>

  </head>
  <Body >

<h1>Test</h1>
<input type="file" id="input"/>
<canvas width="800" height="500" id="canvas"/>

</body>
</html>

      

The above won't work on my chrome or firefox. It seems to display the start page correctly, but the image is not displayed on the canvas.

I think I might have a security issue, or need to wrap it up with a download. Don't understand the syntax for the onload function. js console does not indicate errors.

Any help is appreciated!

Tim

+3


source to share


1 answer


You can select multiple images by adding an attribute multiple

to yours input

.

<input type="file" multiple id="input"/>

      

Here's some sample code a Demo on how to show multiple images as thumbnails on one canvas.



var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var input = document.getElementById('input');
input.addEventListener('change', handleFiles);

function handleFiles(e) {
  //    var images=[];
  var files=e.target.files;
  for(var i=0;i<files.length;i++){
    var img=new Image;
    img.x=i*100;
    img.onload=function(){
      ctx.drawImage(this,this.x,0,80,this.height*(80/this.width));
    }
    img.src=URL.createObjectURL(files[i]);
  }
}
      

body{ background-color: ivory; }
#canvas{border:1px solid red;}
      

<input type="file" multiple id="input"/>
<br>
<canvas id="canvas" width=400 height=300></canvas>
      

Run codeHide result


+1


source







All Articles