LoginSignup
1
2

More than 3 years have passed since last update.

three.js 3dと2dの連携

Posted at

demo https://codepen.io/gnjo/pen/zYBBzzj?editors=1010

 //プレーンを用意して、カメラを別に用意して全面に張る。
 ...
 ///////////////////////////////////////
 // 2d world
 var o2=plane2d(renderer)
 ctx2d=o2.ctx2d,update2d=o2.update2d
 ///////////////////////////////////////  

//レンダリングの順番を指定する
 ...
function animate(){
 requestAnimationFrame(animate)
 renderer.clear() ////for 2d world/////
 renderer.render(scene, camera)
 update3d()
 update2d() /////////2d world//////////
 draw(ctx2d) ///////
}

/////////2d world ////////////////////
function plane2d(renderer){

//レンダリングのオートクリアを外す。
 renderer.autoClear = false;////////////////

 let width=renderer.domElement.width
 ,height=renderer.domElement.height
 ,camera
 ,scene
 ,ctx
 ,canvas
 ;
 //console.log(width,height)

 canvas=document.createElement('canvas')
 canvas.width=width,canvas.height=height
 ctx=canvas.getContext('2d')
 // Create the camera and set the viewport to match the screen dimensions.
 camera = new THREE.OrthographicCamera(-width/2, width/2, height/2, -height/2, 0, 3 );
 scene = new THREE.Scene();

 // Create texture from rendered graphics.
 var tex = new THREE.Texture(canvas) 
 tex.needsUpdate = true;
 tex.minFilter =THREE.NearestFilter;

 // Create HUD material.
 var material = new THREE.MeshBasicMaterial( {map: tex} );
 material.transparent = true;

 // Create plane to render the HUD. This plane fill the whole screen.
 var planeGeometry = new THREE.PlaneBufferGeometry( width, height );
 var plane = new THREE.Mesh( planeGeometry, material );
 scene.add( plane );

 function update2d(){
  tex.needsUpdate = true;    
  renderer.render(scene, camera);  
 }
 return {ctx2d:ctx,update2d:update2d}
}
///////////////////////////////////////
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2