使用scene.background
时,纹理会拉伸以适合窗口大小。
我正在尝试重现MDN page中所述的CSS Cover属性行为:
在不拉伸图像的情况下尽可能放大图像。 如果图像的比例与元素不同,则将其裁切 垂直或水平放置,以确保没有空白空间。
我了解应使用repeat
和offset
纹理属性,但不确定如何使用。
答案 0 :(得分:2)
您遇到同样的问题。挖掘文档后,我解决了它。下面的代码应该可以帮助那些对此感到困惑的人。
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;