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

问题描述 投票:0回答:1

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

不缩放图像就尽可能放大图像。如果图像的比例与元素不同,则将其裁切垂直或水平放置,以确保没有剩余空间。

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

three.js textures
1个回答
0
投票

您遇到同样的问题。挖掘文档后,我解决了它。下面的代码应该可以帮助与此相关的人们。

targetWidth是您的表面或画布的宽度。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;
© www.soinside.com 2019 - 2024. All rights reserved.