赞
踩
效果:
代码:
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>canvas画布作为纹理贴图</title> <script src="../three.js"></script> <script src="../OrbitControls.js"></script></head> <body> <script> var texture; // 1,创建场景对象 var scene = new THREE.Scene(); // 2,使用canvas画图作为纹理贴图 // 先使用canvas画图 var canvas = document.createElement('canvas'); canvas.width = 150; canvas.height = 150; var ctx = canvas.getContext("2d"); ctx.fillStyle = "#ffffff"; var img = new Image(); img.src = "https://img0.baidu.com/it/u=3226103969,2404354919&fm=253&fmt=auto&app=138&f=JPEG?w=634&h=500"; img.crossOrigin = "anonymous"; img.onload = function () { ctx.drawImage(img, 0, 0, 200, 200); texture = new THREE.CanvasTexture(canvas); // texture.needsUpdate = true; // 不设置needsUpdate为true的话,可能纹理贴图不刷新 var plane_geometry = new THREE.PlaneGeometry(100, 100); var material = new THREE.MeshPhongMaterial({ // color:0x11ff22, map: texture, side: THREE.DoubleSide }); var mesh = new THREE.Mesh(plane_geometry, material); scene.add(mesh); } // 创建材质对象 // 3,创建环境光对象 var ambient = new THREE.AmbientLight(0xffffff); scene.add(ambient); // 4,创建相机对象 var width = window.innerWidth; var height = window.innerHeight; var k = width / height; var s = 100; var camera = new THREE.OrthographicCamera(-s * k, s * k, s, -s, -1000, 1000); camera.position.set(200, 300, 200); camera.lookAt(scene.position); // 5,创建渲染器对象 var renderer = new THREE.WebGLRenderer(); renderer.setSize(width, height); document.body.appendChild(renderer.domElement); function render() { renderer.render(scene, camera); requestAnimationFrame(render); } // 创建轴辅助对象 var axes = new THREE.AxesHelper(500); scene.add(axes); // 创建鼠标控制对象 var controls = new THREE.OrbitControls(camera, renderer.domElement); // controls.addEventListener('change',render); render(); </script></body> </html>
说一下遇到的问题:
1,图片使用在线百度图库中的图片时,没有加载 出来,报错 THREE.WebGLState: DOMException: Failed to execute 'texImage2D' on 'WebGLRenderingContext': Tainted canvases may not be loaded. 这是遇到了跨域安全问题,解决方式:
跨域安全问题。跨域;解决办法:安全 1 若是你用的是纹理题图:如:threevar loader = new THREE.TextureLoader();加上:loader.setCrossOrigin( 'Anonymous');方法便可。(THREE.ImageUtils.loadTexture也可用这个方法) 2 若是你是直接用img的,如:imgvar img = new image(); 加上 img.crossOrigin =“anonymous” 便可loader 3 若是你被THREE.WebGLRenderer: image is not power of two 这样的warning所困扰,在你的创建mesh后加上:mesh.material.map.minFilter = THREE.LinearFilter; 便可。如 var mesh = new THREE.Mesh( geometry, material );mesh.material.map.minFilter = THREE.LinearFilter;
2,即使解决了安全策略问题,还是无法显示纹理贴图, , //如果不设置texture.needsUpdate = true ,纹理可能就不会更新,你很可能看到得是黑色几何体。原因是纹理绘制需要一段时间,javascript是可以异步运行的;这里我注释了 texture.needsUpdate = true 这一句,依然能渲染出来,最好是不要注释;上面的Html 中,在创建平面模型 PlaneGeometry ,、高光材质 MeshPhongMaterial 、网格模型 Mesh 时,将他们三者的创建放在了 图片加载完成后进行创建,否则纹理依然无法渲染出来。