Three.js - 缩放背景图像以适应 window,而不拉伸它

Three.js - scaling background image to fit window, without stretching it

当使用 scene.background 时,纹理会被拉伸以适应 window 大小。 我正在尝试重现 MDN page:

中描述的 CSS 封面属性行为

Scales the image as large as possible without stretching the image. If the proportions of the image differ from the element, it is cropped either vertically or horizontally so that no empty space remains.

我知道应该使用 repeatoffset 纹理属性,但我不确定如何使用。

和你一样的问题。挖掘文档后,我解决了它。下面的代码应该适用于为此而苦苦挣扎的人。

targetWidth 是您的表面或 canvas 宽度。 imageWidth 是纹理的宽度需要适合目标。

const targetAspect = targetWidth / targetHeight;
const imageAspect = imageWidth / imageHeight;
const factor = imageAspect / targetAspect;
// When factor larger than 1, that means texture 'wilder' than target。 
// we should scale texture height to target height and then 'map' the center  of texture to target, and vice versa.
scene.background.offset.x = factor > 1 ? (1 - 1 / factor) / 2 : 0;
scene.background.repeat.x = factor > 1 ? 1 / factor : 1;
scene.background.offset.y = factor > 1 ? 0 : (1 - factor) / 2;
scene.background.repeat.y = factor > 1 ? 1 : factor;