2022-10-13 three.js基础学习的基础代码 思来想去,我还是决定把基础代码放到一个地方,供大家参考,每次说复制上一节的代码,感觉比较麻烦。 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108<!DOCTYPE html> <html> <head> <title>three.js学习</title> <meta name="keywords" content=""> <meta name="description" content=""> <meta charset="utf8" /> <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no"> <!-- <script src="https://cdn.bootcdn.net/ajax/libs/three.js/r122/three.min.js"></script> --> <script src="./js/three.min.js"></script> <style> html,body{ height: 100%; margin: 0; } #three{ display: block; width: 100%; height: 100%; } </style> </head> <body> <canvas id="three"></canvas> <script> function getSearchObj (key) { const search = window.location.search.replace('?', '') const list = search.split('&') const obj = {} for (let i = 0; i < list.length; i++) { const eachList = list[i].split('=') obj[eachList[0]] = eachList[1] } return obj[key] } async function main () { const search = location.search const canvas = document.querySelector('#three') const renderer = new THREE.WebGLRenderer({canvas}) const fov = 75; const aspect = 2; const near = 0.1; const far = 200; const camera = new THREE.PerspectiveCamera(fov, aspect, near, far) const group = new THREE.Group() group.position.z = -10 // 在这里写学习的的demo代码 const scene = new THREE.Scene() { const lightColor = 0xffffff; // 灯光颜色 const intensity = 1; // 灯光强度 const light = new THREE.DirectionalLight(lightColor, intensity); light.position.set(10,1,20); light.castShadow = true; scene.add(light); } scene.add(group) function resizeRenderSizeToDisplaySize () { const pixelRatio = window.devicePixelRatio; const displayWidth = canvas.clientWidth * pixelRatio const displayHeight = canvas.clientHeight * pixelRatio const renderWidth = canvas.width; const renderHeight = canvas.height; const needResize = displayWidth !== renderWidth || displayHeight !== renderHeight return needResize } function render (time) { if (resizeRenderSizeToDisplaySize()) { const pixelRatio = window.devicePixelRatio; const width = canvas.clientWidth * pixelRatio const height = canvas.clientHeight * pixelRatio renderer.setSize(width, height, false) camera.aspect = canvas.clientWidth / canvas.clientHeight; camera.updateProjectionMatrix(); } time *= 0.001 group['children'].forEach((each, index) => { if (index !== 1) { each.rotation.x = -time each.rotation.y = -time } }) renderer.render(scene, camera) requestAnimationFrame(render) } requestAnimationFrame(render) // render() } main() </script> </body> </html> Newer three.js基础学习之光源 Older three.js学习之纹理贴图Texture(二)纹理背景的位置移动旋转和重复