使用scene.background
时,纹理被拉伸以适合窗口大小。我正在尝试重现MDN page中描述的CSS Cover属性行为:
不缩放图像就尽可能放大图像。如果图像的比例与元素不同,则将其裁切垂直或水平放置,以确保没有剩余空间。
我知道应该使用repeat
和offset
纹理属性,但不确定如何使用。
您遇到同样的问题。挖掘文档后,我解决了它。下面的代码应该可以帮助与此相关的人们。
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;