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 (簡體中文)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章