如何使用JavaScript获取图像的纵横比。

huangapple go评论88阅读模式
英文:

How to get the aspect ratio of an image using JavaScript

问题

获取原始宽高比this image的期望结果是获得图像的原始宽高比。

英文:

I need to get the original aspect ratio of
this image

Expect to get the original aspect ratio of the image

答案1

得分: 2

将“getAspectRatio()”函数传递一个“img.src”参数。
在获取图片的实际尺寸之后,将检查图片是纵向还是横向格式。
最终,该函数返回图像的宽高比。

function getAspectRatio(image) {

    const w = image.naturalWidth;
    const h = image.naturalHeight;

    let aspectRatio;

    if (w > h) {
        aspectRatio = w / h;
    } else {
        aspectRatio = h / w;
    }

    return aspectRatio;

};
英文:

Pass the "getAspectRatio()" function an "img.src" parameter.
The actual dimensions of the picture will be taken, after which a check will be made whether the picture is in portrait or landscape format.
As a result, the function returns aspect ratio of the image.

function getAspectRatio(image) {

    const w = image.naturalWidth;
    const h = image.naturalHeight;

    let aspectRatio;

    if (w > h) {
        aspectRatio = w / h;
    } else {
        aspectRatio = h / w;
    }

    return aspectRatio;

};

答案2

得分: 1

如果您只需要知道一边比另一边大多少倍,那么其他选项适合您的需求。但如果您想要实际的比例,请尝试这个函数,并将一个HTMLImageElement传递给它。

function aspectRatio(image) {
    const height = image.naturalHeight;
    const width = image.naturalWidth;

    const gcd = (...arr) => {
        const _gcd = (x, y) => (!y ? x : gcd(y, x % y));
        return [...arr].reduce((a, b) => _gcd(a, b));
    };

    const gcdResult = gcd(width, height);

    return `${width / gcdResult}:${height / gcdResult}`;
}

注意:我没有自己编写GCD函数,我从这里偷取了它。

英文:

If you just need to know how many times one side is bigger than the other, then the other options suit your needs. But if you want an actual ratio, try this function and pass it an HTMLImageElement.

function aspectRatio(image) {
    const height = image.naturalHeight;
    const width = image.naturalWidth;

    const gcd = (...arr) => {
        const _gcd = (x, y) => (!y ? x : gcd(y, x % y));
        return [...arr].reduce((a, b) => _gcd(a, b));
    };

    const gcdResult = gcd(width, height);

    return `${width / gcdResult}:${height / gcdResult}`;
}

Note: I didn't write write the GCD function myself, I stole it from here.

答案3

得分: 0

尝试这样做:

const aspectRatio = yourImage.naturalWidth / yourImage.naturalHeight;

console.log('纵横比:', aspectRatio);
英文:

Try this :

const aspectRatio = yourImage.naturalWidth / yourImage.naturalHeight;

console.log('Aspect ratio:', aspectRatio);

huangapple
  • 本文由 发表于 2023年6月15日 01:45:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76476276.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定