Three.js 不拉伸网格纹理(图像) - 使其覆盖其容器

2023-12-27

我有一个容器,我使用 Three.js 和网格应用图像。

这就是我将网格应用到场景的方式:

this.$els = {
    el: el,
    image: el.querySelector('.ch__image') <-- size of container image is being applied to
};

this.loader = new THREE.TextureLoader();
this.image = this.loader.load(this.$els.image.dataset.src);
this.sizes = new THREE.Vector2(0, 0);
this.offset = new THREE.Vector2(0, 0);

getSizes() {
    const { width, height, top, left } = this.$els.image.getBoundingClientRect();

    this.sizes.set(width, height);
    this.offset.set(left - window.innerWidth / 2 + width / 2, -top + window.innerHeight / 2 - height / 2)
}

createMesh() {
    this.geometry = new THREE.PlaneBufferGeometry(1, 1, 1, 1);
    this.material = new THREE.MeshBasicMaterial({
        map: this.image
    });

    this.mesh = new THREE.Mesh(this.geometry, this.material);

    this.mesh.position.set(this.offset.x, this.offset.y, 0);
    this.mesh.scale.set(this.sizes.x, this.sizes.y, 1);

    this.scene.add(this.mesh)
}

目前图像/纹理正在被拉伸以适合容器 - 我怎样才能使行为就像object-fit: cover or background-size: cover?


尝试使用cover()此代码片段中呈现的函数。这个想法是使用容器和图像的方面来实现类似的结果,例如background-size: cover.

var camera, scene, renderer;

var texture;

init();
animate();

function init() {

    camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 10 );
    camera.position.z = 1;

    scene = new THREE.Scene();

    texture = new THREE.TextureLoader().load( 'https://threejs.org/examples/textures/crate.gif', () => {
    
      cover( texture, window.innerWidth / window.innerHeight );
    
      scene.background = texture;
    
    } );
    texture.matrixAutoUpdate = false;

    renderer = new THREE.WebGLRenderer( { antialias: true } );
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );
    
    window.addEventListener( 'resize', onWindowResize, false );

}

function onWindowResize() {

  var aspect = window.innerWidth / window.innerHeight;

  camera.aspect = aspect;
  camera.updateProjectionMatrix();
  
  cover( texture, aspect );

  renderer.setSize( window.innerWidth, window.innerHeight );

}

function cover( texture, aspect ) {

  var imageAspect = texture.image.width / texture.image.height;

  if ( aspect < imageAspect ) {

      texture.matrix.setUvTransform( 0, 0, aspect / imageAspect, 1, 0, 0.5, 0.5 );

  } else {

      texture.matrix.setUvTransform( 0, 0, 1, imageAspect / aspect, 0, 0.5, 0.5 );

  }

}

function animate() {

    requestAnimationFrame( animate );
    renderer.render( scene, camera );

}
body {
  margin: 0;
 }
 canvas {
  display: block;
 }
<script src="https://cdn.jsdelivr.net/npm/[email protected] /cdn-cgi/l/email-protection/build/three.js"></script>

顺便说一句:而不是使用window.innerWidth and window.innerHeight,请改用容器的尺寸。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Three.js 不拉伸网格纹理(图像) - 使其覆盖其容器 的相关文章

随机推荐