Reputation: 193
I have found a lot of tutorials on html5 image upload e.g.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type='text/javascript' src='/js/lib/mootools-core-1.4.5-nocompat.js'></script>
<link rel="stylesheet" type="text/css" href="/css/normalize.css">
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style type='text/css'>
</style>
<script type='text/javascript'>//<![CDATA[
window.addEvent('load', function() {
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
var canvas = document.getElementById('imageCanvas');
var ctx = canvas.getContext('2d');
function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
});//]]>
</script>
</head>
<body>
<label>Image File:</label><br/>
<input type="file" id="imageLoader" name="imageLoader"/>
<canvas id="imageCanvas"></canvas>
</body>
</html>
But how would I preview an image without it overwriting the previous. I want to be able to upload as many images as I like and just have them horizontally aligned or positioned according to a style sheet.
Upvotes: 0
Views: 1830
Reputation: 66388
First of all, add a placeholder that will hold all the images selected by user:
<div id="Placeholder">
<canvas id="imageCanvas"></canvas>
</div>
Now the required JS code to add the selected picture to the placeholder every time is:
window.onload = function() {
var counter = 0;
var imageLoader = document.getElementById('imageLoader');
var oPlaceholder = document.getElementById('Placeholder');
imageLoader.addEventListener('change', handleImage, false);
var originalCanvas = document.getElementById('imageCanvas');
function handleImage(e){
counter++;
var canvas = originalCanvas.cloneNode(true);
canvas.id += "_" + counter;
oPlaceholder.appendChild(canvas);
var ctx = canvas.getContext('2d');
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
};
Upvotes: 1