$(function() {
$("#file_select").change(function(e) {
var fileReader = new FileReader();
fileReader.onload = function(e) {
var img = new Image();
img.onload = function() {
var MAX_WIDTH = 100;
var MAX_HEIGHT = 100;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
console.log('looping');
var canvas = document.createElement("canvas");
// canvas.setAttribute('id', 'canvas')
canvas.width = width;
canvas.height = height;
canvas.getContext("2d").drawImage(this, 0, 0, width, height);
// //Line added
var canvasData = canvas.toDataURL();
// //Line edited
this.src = canvasData;
// //Line added
console.log(canvasData.length * 3 / 4, ' bytes');
document.body.appendChild(this); //remove this if you don't want to show it
}
img.src = e.target.result;
}
fileReader.readAsDataURL(e.target.files[0]);
});
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<h1 class="logo">Upload Picture</h1>
<div id="upload_form_div">
<form id="upload_form" method="POST" enctype="multipart/form-data" action="upload">
<input type="file" name="file" capture="camera" id="file_select" />
</form>
</div>
<div id="loading" style="display:none;">
Uploading your picture...
</div>
它工作得很好,图像大小和返回大小的文件,但我面临的问题是
canvas
元素不停地在里面创造
img.onload = function(){...}
发生了什么事,我怎么能摆脱这一切?谢谢