三个 JS - 缩放纹理以完美地适合(任何大小)平面



本质上,我想复制CSS的行为,background-size: cover的工作方式。

看这里,你可以看到图像正在缩放,保持其纵横比,但它并没有真正正常工作,因为图像没有填满平面,留下两侧的边距 - https://next.plnkr.co/edit/8650f9Ji6qWffTqE?preview

代码片段(第 170 - 175 行( -

var geometryAspectRatio = 5/3;
var imageAspectRatio = 3264/2448;
textTile.wrapT = THREE.RepeatWrapping;
textTile.repeat.x = geometryAspectRatio / imageAspectRatio; 
textTile.offset.x = 0.5 * ( 1 - textTile.repeat.x );

我想发生的是让它扩大规模,然后将自身重新定位在中心(cover的工作方式(。

var repeatX, repeatY;
repeatX = w * this.textureHeight / (h * this.textureWidth);
if (repeatX > 1) {
//fill the width and adjust the height accordingly
repeatX = 1;
repeatY = h * this.textureWidth / (w * this.textureHeight);
mat.map.repeat.set(repeatX, repeatY);
mat.map.offset.y = (repeatY - 1) / 2 * -1;
} else {
//fill the height and adjust the width accordingly
repeatX = w * this.textureHeight / (h * this.textureWidth);
repeatY = 1;
mat.map.repeat.set(repeatX, repeatY);
mat.map.offset.x = (repeatX - 1) / 2 * -1;
}

更新 https://next.plnkr.co/edit/LUk37xLG2yvv6hgg?preview

对于像我这样对此感到困惑的人来说,对我来说缺少的部分是任何纹理的 .repeat.x 和 .repeat.y 属性的值都可以小于 1,并在小于 1 时放大图像作为比例的反比。 想想看,当它是比例为2时,在某种程度上它会重复0.5次,因为你只能看到图像的一半。

所以。。。 THREE中的纹理不支持的东西.js并且在某些库中很常见,将是

.scaleX = 2;(自 v1.30.1 起不支持 THREE.js 纹理(

三.js纹理等效物将是

texture.repeat.x = .5;

要将比例转换为"重复",只需执行比例的反转

var desiredScaleX = 3;
var desiredRepeatX = 1 / desiredScaleX;

刻度 3 的重复结果为 (1/3( = .3333; 换句话说,3x 图像将被裁剪,只显示图像的 1/3,因此它会重复 .3333 次。

至于缩放以适应覆盖,通常选择两者中较大的比例就可以了,例如:

var fitScaleX = targetWidth / actualWidth;
var fitScaleY = targetHeight / actualHeight;
var fitCoverScale = Math.max(fitScaleX,fitScaleY);
var repeatX = 1 / fitCoverScale;
var repeatY = 1 / fitCoverScale;

最新更新