我有这些功能
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
var img = new Image;
img.src = reader.result;
var imgwidth = img.width;
var imgheight = img.height;
console.log(imgwidth);
console.log(imgheight);
$('#imgcrop').attr('src', e.target.result);
$('#preview').attr('src', e.target.result);
$('.crop').Jcrop({
onSelect: updateCoords,
boxWidth: 300,
boxHeight: 300,
onChange: showPreview,
aspectRatio: 1,
bgOpacity: .4,
setSelect: [ 100, 100, 50, 50 ]
});
};
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function() {
console.log(this);
readURL(this);
});
function updateCoords(c) {
console.log(c);
$('#x').val(c.x);
$('#y').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
}
function showPreview(coords) {
var rx = 100 / coords.w;
var ry = 100 / coords.h;
$('#preview').css({
width: Math.round(rx * imgwidth) + 'px',
height: Math.round(ry * imgheight) + 'px',
marginLeft: '-' + Math.round(rx * coords.x) + 'px',
marginTop: '-' + Math.round(ry * coords.y) + 'px'
});
}
我需要从文件阅读器函数中访问imgwidth和imgheight以在showpreview函数中使用,但我在这些函数的范围方面遇到了问题。如何访问这些值,或者至少将它们作为参数传递给其他函数使用?
谢谢!
答案 0 :(得分:0)
将它们作为参数传递给showPreview
:
function showPreview(coords, imgheight, imgwidth) {
var rx = 100 / coords.w;
var ry = 100 / coords.h;
$('#preview').css({
width: Math.round(rx * imgwidth) + 'px',
height: Math.round(ry * imgheight) + 'px',
marginLeft: '-' + Math.round(rx * coords.x) + 'px',
marginTop: '-' + Math.round(ry * coords.y) + 'px'
});
}
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
var img = new Image;
img.src = reader.result;
var imgwidth = img.width;
var imgheight = img.height;
console.log(imgwidth);
console.log(imgheight);
$('#imgcrop').attr('src', e.target.result);
$('#preview').attr('src', e.target.result);
$('.crop').Jcrop({
onSelect: updateCoords,
boxWidth: 300,
boxHeight: 300,
onChange: function(coords) {
showPreview(coords, imgheight, imgwidth);
},
aspectRatio: 1,
bgOpacity: .4,
setSelect: [ 100, 100, 50, 50 ]
});
};
reader.readAsDataURL(input.files[0]);
}
}