验证中...
开源中国 2018 年度最后一场技术盛会邀你来约~错过就要等明年啦!点此立即预约
语言: JavaScript
分类: JavaScript 工具
最后更新于 2018-12-09 10:33
gistfile1.txt
原始数据 复制代码
$(function() {
FastClick.attach(document.body);
$("#file").change(function(e){
var reader = new FileReader();
//预览
var file = e.target.files[0];
resize(event, function(base64){
$(".preview").attr("src", base64).show();
});
});
$("#submit_btn").click(function(){
var form = $(this).parents("form");
if(form.find("#file").val() === ""){
$.toptip('参加活动需要选择您的美照哦', 'warning');
return false;
}
});
});
//限制图片尺寸,最大为100*100
function resize(event, callback){
var file = event.currentTarget.files[0];
var reader = new FileReader();
reader.onload = function(e){
console.log(e);
var img = new Image();
var width = img.naturalWidth,
height = img.naturalHeight;
var b = height/width;
img.onload = function(e){
//console.log(this);
var originWidth = this.width;
var originHeight = this.height;
// 最大尺寸限制
var maxWidth = 1000, maxHeight = 1000;
// 目标尺寸
var targetWidth = originWidth, targetHeight = originHeight;
// 图片尺寸超过400x400的限制
if (originWidth > maxWidth || originHeight > maxHeight) {
if (originWidth / originHeight > maxWidth / maxHeight) {
// 更宽,按照宽度限定尺寸
targetWidth = maxWidth;
targetHeight = Math.round(maxWidth * (originHeight / originWidth));
} else {
targetHeight = maxHeight;
targetWidth = Math.round(maxHeight * (originWidth / originHeight));
}
}
var canvas = document.createElement('canvas');
canvas.width = targetWidth;
canvas.height = targetHeight;
var context = canvas.getContext("2d");
context.clearRect(0, 0, targetWidth, targetHeight);
context.drawImage(this, 0, 0, targetWidth, targetHeight);
var data = canvas.toDataURL("image/jpeg");
//canvas.toBlob(function(blob){
// callback(blob);
//});
callback(data);
//this.src = data;
//console.log("11");
}
img.src = e.currentTarget.result;
img.style.marginBottom = 80;
}
reader.readAsDataURL(file);
console.log(event);
}

评论列表( 0 )

你可以在登录后,发表评论

搜索帮助