Three.js - 缩放背景图像以适合窗口,而不拉伸它

The*_*Cat 3 textures three.js

使用时,scene.background纹理会被拉伸以适合窗口大小。我正在尝试重现MDN 页面上描述的 CSS cover 属性行为:

在不拉伸图像的情况下将图像缩放得尽可能大。如果图像的比例与元素不同,则会垂直或水平裁剪图像,以便不留任何空白空间。

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

ooO*_*lly 7

和你有同样的问题。挖掘文档后我解决了它。下面的代码应该适用于遇到此问题的人。

\n\n

targetWidth是您的表面或画布宽度。\nimageWidth是需要适合目标的纹理宽度。

\n\n
const targetAspect = targetWidth / targetHeight;\nconst imageAspect = imageWidth / imageHeight;\nconst factor = imageAspect / targetAspect;\n// When factor larger than 1, that means texture 'wilder' than target\xe3\x80\x82 \n// we should scale texture height to target height and then 'map' the center  of texture to target\xef\xbc\x8c and vice versa.\nscene.background.offset.x = factor > 1 ? (1 - 1 / factor) / 2 : 0;\nscene.background.repeat.x = factor > 1 ? 1 / factor : 1;\nscene.background.offset.y = factor > 1 ? 0 : (1 - factor) / 2;\nscene.background.repeat.y = factor > 1 ? 1 : factor;\n
Run Code Online (Sandbox Code Playgroud)\n