»
064. JS Calculate DPI
业余时间,我在threejs的开发过程中,遇到了不同分辨率的屏幕显示threejs的火箭喷射器的效果不一样的情况,特别是1920*1080的屏幕,粒子效果中的粒子特别大。
查找原因后,最后发现是屏幕的DPI不同导致。在DPI的计算方面做个总结。
网页的DPI计算需要使用尺寸单位inch:
<div id='testdiv' style='height: 1in; left: -100%; position: absolute; top: -100%; width: 1in;'></div>
<script type='text/javascript'>
// 以下是错误的计算DPI的方法
// const screenWidth = window.screen.width; // 获取屏幕宽度(单位:像素)
// const screenHeight = window.screen.height; // 获取屏幕高度(单位:像素)
// const physicalWidth = window.screen.width / window.devicePixelRatio; // 计算屏幕物理宽度(单位:英寸)
// const physicalHeight = window.screen.height / window.devicePixelRatio; // 计算屏幕物理高度(单位:英寸)
// 以下是正确的计算DPI的方法
var dpi_x = document.getElementById('testdiv').offsetWidth;//横向dpi
var dpi_y = document.getElementById('testdiv').offsetHeight;//纵向dpi
var devicePixelRatio = window.devicePixelRatio || 1;//屏幕缩放率
var dpi_x_ratio = document.getElementById('testdiv').offsetWidth / devicePixelRatio;//屏幕缩放后的横向dpi
var dpi_y_ratio = document.getElementById('testdiv').offsetHeight / devicePixelRatio;//屏幕缩放后的纵向dpi
console.log(dpi_x, dpi_y, devicePixelRatio, dpi_x_ratio, dpi_y_ratio);
</script>
在threejs的网页3D开发过程中要保持粒子效果的粒子在低分辨率设备上能够正确显示,就需要对renderer做如下设置:
renderer.setPixelRatio(192 / dpi_x);
————www.v-signon.com学习者共勉