three.js中場景模糊、紋理失真的問題


1. 概述

在three.js場景中,有時會遇到場景模糊,紋理失真的現象,似乎three.js並沒有用到紋理圖片應有的分辨率。可以通過相關設置來解決這個問題。

2. 方案

2.1. 開啟反走樣

three.js創建的WebGLRenderer對象有抗鋸齒選項的支持:

var renderer = new THREE.WebGLRenderer({
    antialias: true,     //抗鋸齒
});

這個選項默認是關閉的,所以需要顯式開啟一下。

2.2. 開啟HiDPI設置

如果開啟抗鋸齒后仍然顯示比較模糊,那么可能就是使用的是HiDPI (High Dots Per Inch) 設備顯示造成的,HiDPI設備能在較小尺寸下顯示出較高分辨率,也就是每一個屏幕上的物理像素其實是由多個像素顯示出來的,所以需要設置一下設備像素比率:

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

其實關於HiDPI的討論還是挺多的,比如說有個縮放與布局設置:
imglink1

這個設置會更改window.devicePixelRatio的值,如果程序不做相關的設置,那么程序的UI顯示出來就會是模糊的。現代程序組件一般都會自動做出相關的調整,在WebGL中則需要顯式設置一下。

3. 結果

測試代碼:

'use strict';

function init() {
    //console.log("Using Three.js version: " + THREE.REVISION);   

    // create a scene, that will hold all our elements such as objects, cameras and lights.
    var scene = new THREE.Scene();

    // create a camera, which defines where we're looking at.
    var camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);

    // create a render and set the size
    var renderer = new THREE.WebGLRenderer({
        antialias: true,     //抗鋸齒
    });
    renderer.setClearColor(new THREE.Color(0x000000));    
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(window.innerWidth, window.innerHeight);

    // add the output of the renderer to the html element
    document.getElementById("webgl-output").appendChild(renderer.domElement);


    var loader = new THREE.TextureLoader();
    loader.setCrossOrigin('Anonymous');
    var basePath = "1.jpg";
    loader.load(basePath, function (texture) {
        // create the ground plane
        var planeGeometry = new THREE.PlaneGeometry(2, 2);
        // var planeMaterial = new THREE.MeshBasicMaterial({
        //     color: 0xAAAAAA
        // });
        var planeMaterial = new THREE.MeshBasicMaterial({
            map: texture
        });

        var plane = new THREE.Mesh(planeGeometry, planeMaterial);

        // add the plane to the scene
        scene.add(plane);

        renderer.render(scene, camera);
    });
}

關閉反走樣以及HiDPI:
imglink2

開啟反走樣以及HiDPI之后顯示效果有所改善:
imglink3

4. 參考

  1. 關於ThreeJS場景失真的問題
  2. 關於three.js 抗鋸齒
  3. HiDPI (簡體中文)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM