javascript - 最优雅的图像到图像帧比较算法

标签 javascript

我有兴趣找到这个问题的最优雅和“正确”的解决方案。我是 JS/PHP 的新手,很高兴能使用它。目标是将给定图像的大小与图像“框架”的大小(最终将是 <div><li>)进行比较,并相应地调整图像大小。用户将上传多种尺寸和形状的图像,并且框架也会有多种尺寸和形状。目标是确保任何给定图像都能正确调整大小以适合任何给定框架。最终的实现将在 PHP 中进行,但我正在 JS 中制定逻辑。这是我所拥有的:

//predefined variables generated dynamically from other parts of script, these are example values showing the 'landscape in landscape' ratio issue
var $imageHeight = 150, $imageWidth = 310, $height = 240, $width = 300;         
//check image orientation
if ( $imageHeight == $imageWidth ) {
    var $imageType = 1; // square image
} else if ( $imageHeight > $imageWidth ) {
    var $imageType = 2; // portrait image
} else {
    var $imageType = 3; // landscape image
};
//check frame orientation and compare to image orientation
if ( $height == $width) { //square frame
    if ( ( $imageType === 1 ) || ( $imageType === 3 ) ) {
        $deferToHeight = true;
    } else {
        $deferToHeight = false;
    };
} else if  ( $height > $width ) { //portrait frame
    if ( ( $imageType === 1 ) || ( $imageType === 3 ) )  {
        $deferToHeight = true;
    } else {
        if (($imageHeight / $height) < 1) {
                $deferToHeight = true;
            } else {
                $deferToHeight = false;
        };
    };
} else { //landscape frame
    if ( ( $imageType === 1 ) || ( $imageType === 2 ) ) {
        $deferToHeight = false;
    } else {
        if (($imageWidth / $width) > 1) {
                $deferToHeight = true;
            } else {
                $deferToHeight = false;
        };
    };
};
//set values to match (null value scales proportionately)
if ($deferToHeight == true) { //defer image size to height of frame
    $imageWidth = null;
    $imageHeight = $height;
} else { //defer image size to width of frame
    $imageWidth = $width;
    $imageHeight = null;
};

我已经用一堆不同的值对其进行了测试,它有效,但我怀疑我可以实现一个更优雅的解决方案。我可以在哪些方面做得更好?

最佳答案

这是我最近在 JS 实现中处理这个确切问题的方法:

// determine aspect ratios
var a1 = imageWidth / imageHeight,
    a2 = frameWidth / frameHeight,
    widthDetermined = a1 > a2;

// set scale
var scale = widthDetermined ?
    // scale determined by width
    frameWidth / imageWidth :
    // scale determined by height
    frameHeight / imageHeight;

// set size (both dimensions) based on scale
imageWidth = scale * imageWidth;
imageHeight = scale * imageHeight;

代码比您的版本少得多。请注意,方形情况可以以任何一种方式处理,这在您的版本中也可能是正确的。

关于javascript - 最优雅的图像到图像帧比较算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9304140/

相关文章:

javascript - 使用 javascript 和 Angularjs 循环

javascript - iMacros TAG 查找 TXT 并单击附近的(上一个)链接

javascript - 如何将 setState 传递给另一个组件

javascript - 如何使用 EmberData 在 EmberJS 中返回由嵌套模型组成的 promise ?

javascript - 单击调整 Canvas 图像的大小并使用 javascript 将其居中

javascript - 使 z-index 子级高于父级

javascript - 如何使用 jquery 定位下拉选择器

javascript - 类型 '{ state: any; dispatch: React.Dispatch<{ type: string; value: any; }>; }' 不可分配给类型

Javascript 跨浏览器输入层

javascript - 如果悬停在其他链接上,需要停用点击功能