vue + threejs项目:TextureLoader纹理贴图不显示图片(显示黑色)的问题(解决篇)
原因分析 · 解决办法:
第一种:物体材质不对
- 改用下述代码试下:
const geometry = new THREE.PlaneGeometry(204, 102);
第二种:导入的方式不对
- 如果是vue项目,基于vue导入图片,则需要改成require的引入方式,代码如下:
// 创建基础几何模型(在场景中添加几何物品)
// const geometry = new THREE.BoxGeometry('X轴的长', 'Y轴的长', 'Z轴的长')
const geometry = new THREE.BoxGeometry(2,2,2)
// 创建纹理贴图
const texture = new THREE.TextureLoader().load(require("@/views/example/vr/images/wenli_03.png"));// 或者相对路径'./images/wenli_03.png'
// 创建材质
const material = new THREE.MeshBasicMaterial({
// color: 0x00ff00,
map: texture
});
附:案例源码:
- 全部案例 · 源码示下:
<template>
<div class="app-container">
<div ref="container" id="container"></div>
</div>
</template>
<script>
import * as THREE from 'three'
export default {
name: 'VR',
data() {
return {
sceneUrl: 'http://localhost:81/static/img/profile.473f5971.jpg', // 需要预览的图片绝对路径
camera: null,
scene: null,
renderer: null,
isUserInteracting: false,
onPointerDownPointerX: 0,
onPointerDownPointerY: 0,
lon: 0,
onPointerDownLon: 0,
lat: 0,
onPointerDownLat: 0,
phi: 0,
theta: 0,
target: new THREE.Vector3()
}
},
mounted() {
this.init();
},
methods: {
init(){
console.log("init")
//1. 创建场景和摄像机
const scene = new THREE.Scene();
// 2. 创建摄像机
// const camera = new THREE.PerspectiveCamera('视角', '指投影窗口的长宽比', '表示从距离摄像机多远的位置开始渲染', '表示距离摄像机多远的位置截止渲染 1000')
const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1 , 1000)
// 创建ThreeJS渲染器
const renderer = new THREE.WebGLRenderer({antialias: true});// new THREE.WebGLRenderer();
// 设置渲染器场景的大小
renderer.setSize(window.innerWidth, window.innerHeight)
// 把渲染器添加到我们的页面中去
// document.body.appendChild(renderer.domElement);
this.$refs.container.appendChild(renderer.domElement)
// 创建基础几何模型(在场景中添加几何物品)
// const geometry = new THREE.BoxGeometry('X轴的长', 'Y轴的长', 'Z轴的长')
const geometry = new THREE.BoxGeometry(2,2,2)
// 创建纹理贴图
const texture = new THREE.TextureLoader().load(require("@/views/example/vr/images/wenli_03.png"));
// 创建材质
const material = new THREE.MeshBasicMaterial({
// color: 0x00ff00,
map: texture
});
// 创建网络对象
const cube = new THREE.Mesh(geometry, material);
// 把网格对象添加到场景中去
scene.add(cube)
//添加帧渲染
function animate(){
requestAnimationFrame(animate)
// 网格对象自动旋转
cube.rotation.x += 0.01
cube.rotation.y += 0.01
// 渲染器渲染场景和照相机
renderer.render(scene, camera)
}
animate()
// 摄像机空间Z轴位置
camera.position.z = 6;// 数值越大,模型距离屏幕感觉越远
// 动态响应窗口缩放尺寸
window.addEventListener('resize', () => {
// 初始化摄像机
camera.aspect = window.innerWidth/window.innerHeight;
camera.updateProjectionMatrix()// 初始化摄像机矩阵投影
// 初始化渲染器尺寸
renderer.setSize(window.innerWidth, window.innerHeight)
})
},
}
}
</script>
<style type="text/css">
#container {
width: 100%;
height: 100vh;
background: #eee;
}
</style>
>以上就是关于“vue + threejs项目:TextureLoader纹理贴图不显示图片(显示黑色)的问题(解决篇)”的全部内容。