javascript - Resizing view in three.js shrinks image -
i trying create online 3d manipulation tool. have got three.js view set rotating cube , grid. when run code works 100% fine, if resize view not adjust three.js screen it. (it shrinks length or width of scene depending on how browser view changes.) causing view distorted.
$(function(){ var scene = new three.scene(); var camera = new three.perspectivecamera(45, window.innerwidth / window.innerheight, .1, 500); var renderer = new three.webglrenderer(); renderer.setclearcolor(0xdddddd); renderer.setsize(window.innerwidth, window.innerheight); renderer.shadowmap.enabled = true; renderer.shadowmapsoft = true; var axis = new three.axishelper(10); scene.add(axis); var color = new three.color("rgb(255,0,0)"); var color2 = new three.color(0xd3d3d3); var grid = new three.gridhelper(50, 15, color, color2); scene.add(grid); var cubegeometry = new three.boxgeometry(5, 5, 5); var cubematerial = new three.meshlambertmaterial({color: 0xff3300}); var cube = new three.mesh(cubegeometry, cubematerial) /*var planegeometry = new three.planegeometry(30, 30, 30); var planematerial = new three.meshlambertmaterial({color: 0xffffff}); var plane = new three.mesh(planegeometry, planematerial); plane.rotation.x = -.5*math.pi; plane.position.y = -.1 plane.recieveshadow = true; scene.add(plane);*/ cube.position.x = 2.5; cube.position.y = 4; cube.position.z = 2.5; cube.castshadow = true; scene.add(cube); var spotlight = new three.spotlight(0xffffff); spotlight.castshadow = true; spotlight.position.set(15, 30, 50); scene.add(spotlight); camera.position.x = 40; camera.position.y = 40; camera.position.z = 40; camera.lookat(scene.position); var guicontrols = new function(){ this.rotationx = 0.01; this.rotationy = 0.01; this.rotationz = 0.01; } var datgui = new dat.gui(); datgui.add(guicontrols, 'rotationx', 0, 1); datgui.add(guicontrols, 'rotationy', 0, 1); datgui.add(guicontrols, 'rotationz', 0, 1); render(); function render() { //me trying reset camera view every render camera.fov = 45 camera.aspect = window.innerwidth / window.innerheight camera.near = .1 camera.far = 500 scene.add(camera); cube.rotation.x += .1; renderer.setsize(window.innerwidth, window.innerheight); requestanimationframe(render); renderer.render(scene, camera); } $("#world").append(renderer.domelement); renderer.render(scene, camera); });
add event listener in code handle resize:
window.addeventlistener( 'resize', onwindowresize, false );
and then:
function onwindowresize() { w = window.innerwidth; h = window.innerheight; camera.aspect = w / h; camera.updateprojectionmatrix(); renderer.setsize( w, h ); }
or, since using jquery, can add instead:
$( window ).resize(function() { w = window.innerwidth; h = window.innerheight; camera.aspect = w / h; camera.updateprojectionmatrix(); renderer.setsize( w, h ); });
click here see working codepen.
Comments
Post a Comment