How to properly scale the renderer?

Hi,

I’m having a scaling issue where I want my canvas to be sized to my preferences.

For context, I’m trying to make the canvas generated by Three.js to { width: 800, height: 512 } but the canvas results with this:

// Why the width to 1250 and the height to 800?
<canvas width="1250" height="800" style="display: block; width: 800px; height: 512px;"></canvas>

instead of this

<canvas width="800" height="512" style="display: block; width: 800px; height: 512px;"></canvas>

I’ve tried many things and now it looks like this and the canvas is sized to my preferences like above but I’m having a scaling issue.

How it is supposed to look like (but the canvas is set to the wrong width and height 1250, 800)

renderer.setSize(800, 512);
renderer.setPixelRatio(800 / 512);
renderer.domElement.width = 800;
renderer.domElement.height = 512;
camera.updateProjectionMatrix();

Now, since I’m integrating this in a React app, it uses props.

renderer.setSize(props.width, props.height);
renderer.setPixelRatio(props.width / props.height);
renderer.domElement.width = props.width;
renderer.domElement.height = props.height;
camera.updateProjectionMatrix();

// Doing it with the props makes the canvas sizes to 
<canvas width="1250" height="800" style="display: block; width: 800px; height: 512px;"></canvas>

// How I'm calling my component
<ThreeGT
  width={800}
  height={512}
/>

What am I doing wrong? How can I fix this scaling problem? Are the props an issue?

I just want the canvas set to the code below and everything looking fine. (Without the scaling problem)

<canvas width="800" height="512" style="display: block; width: 800px; height: 512px;"></canvas>

Not sure if providing some more information can help but here is the HTML/CSS:

<>
<div className='gatefoldAnim' ref={mount} /> // Three.js
  <style jsx>{`
    .gatefoldAnim {
       display: block;
       width: ${800}px;
       height: ${512}px;
     }
  `}</style>
</>

If someone can point me in the right direction, I’d be more than grateful and If you’d like more information, I am more than happy to share it with you.

Cheers,
Alan

Hey,

I am not shure about the React implementation but maybe it is a problem to set the renderers pixel ratio with your aspect ratio.

You could delete that line:

renderer.setPixelRatio(props.width / props.height);

or honor the devices pixel ration like this: (which is good practice)

renderer.setPixelRatio(window.devicePixelRatio)

also set your camera to these values:

camera.aspect = props.width / props.height;
camera.updateProjectionMatrix();

or do this directly when instanciating the camera (second parameter)

maybe thats a starting point…

1 Like

Thank you so much, it worked!

1 Like