访问来自另一个函数的函数结果

Accessing function results from another function?

本文关键字:函数 结果 另一个 访问      更新时间:2023-09-26

我有这些函数

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函数中使用,但我在这些函数的范围方面遇到了问题。我如何访问这些值,或者至少将它们作为参数传递给其他函数?

谢谢!

将它们作为参数传递给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]);
    }
}