I want to resize the canvas but keep the aspect ratio of the object. When I make the canvas ~9:16 it distorts.
I have the usual
const canvas = document.getElementById("three");
const scene = new THREE.Scene();
const renderer = new THREE.WebGLRenderer({
antialias: true,
canvas: canvas,
//? set the renderer's background to be transparent
alpha: true,
});
// const canvas = document.body.appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
window.addEventListener("resize", onWindowResize, false);
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
I tried setting the camera aspect ratio to the canvas’ width and height like in here , but that didn’t work.
lolia
September 11, 2022, 5:40pm
2
Hi
window.addEventListener("resize", onWindowResize());
onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
You resize something, but window, so the event doesn’t fire.
Also, you need to take in count not window size, but the size of renderer. If I got correctly, what you’re trying to achieve.
I did try adding the event listener to the canvas before posting, also didn’t work; if that’s what you mean.
Do you change canvas size with code?
So after renderer.setSize(desiredWidth, desiredHeight);
add
camera.aspect = desiredWidth / desiredHeight;
camera.updateProjectionMatrix();
2 Likes
Listening for size changes of a dom element is difficult, as well as @prisoner849 suggestion you can use the observer api
This is how I fixed it (the height was incorrect maybe because it was getting inquired before it changed)
const canvas = document.getElementById("three");
function getWidth() {
return parseInt(window.getComputedStyle(canvas).width);
}
function getHeight() {
return parseInt(window.getComputedStyle(canvas).height);
}
//? core
const scene = new THREE.Scene();
const renderer = new THREE.WebGLRenderer({
antialias: true,
canvas: canvas,
//? set the renderer's background to be transparent
alpha: true,
});
const camera = new THREE.PerspectiveCamera(75, getWidth() / getHeight(), 0.1, 1000);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
addEventListener("resize",() => {
camera.aspect = getWidth() / getHeight();
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
},false);
I ran into another issue though, the camera doesn’t fit the whole object now.
1 Like