我找到了很多关于html5图片上传的教程,例如。
<!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>
但是如果没有覆盖之前的图像,我将如何预览图像。我希望能够上传尽可能多的图像,并根据样式表将它们水平对齐或定位。
答案 0 :(得分:1)
首先,添加一个占位符,用于保存用户选择的所有图像:
<div id="Placeholder">
<canvas id="imageCanvas"></canvas>
</div>
现在每次都要将所选图片添加到占位符所需的JS代码是:
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]);
}
};