0

In CSS, I can do it like:

<div class="aspect-ratio-box"></div>
body {
  max-width: 1366px;
  margin: 0 auto;
  padding: 20px;
}

.aspect-ratio-box {
  height: 0;
  padding-top: 56.25%;
  background: red;
}

Here's the CodePen. Try resizing the browser window to see how it maintains aspect ratio.

But I can't wrap my head around on how to do it with Konva, especially React Konva where I have to maintain aspect ratio using width, height & aspectRatio. There is no padding-top.

How should I do it?

Note: It looks similar to How to resize images proportionally / keeping the aspect ratio? but I have tried this solution & it jumps up from original position (width=1024, height=600) when I shrink the browser but when I grow it again it never returns to the original position (width=1024, height=600)

This is what I want my app to look like:

browser-window

Basically I want to accomplish the white part in the center in JS because I need to use Canvas.

deadcoder0904
  • 7,232
  • 12
  • 66
  • 163
  • Does this answer your question? [How to resize images proportionally / keeping the aspect ratio?](https://stackoverflow.com/questions/3971841/how-to-resize-images-proportionally-keeping-the-aspect-ratio) – oguzhancerit Dec 25 '20 at 12:20
  • @oguzhancerit nope, i already checked this solution → https://stackoverflow.com/a/14731922/6141587 which is close but the initial position (width=1024, height=600) is never obtained again. i would love to solve this but cant seem to figure out a way that doesn't use CSS's `padding-top` & can purely do it in JS but has output like https://codepen.io/chriscoyier/pen/BZNoev – deadcoder0904 Dec 25 '20 at 13:01
  • @oguzhancerit i edited the question with an image..i've shown what im trying to accomplish if that makes sense :) – deadcoder0904 Dec 25 '20 at 13:15

1 Answers1

1

I found a real cool solution that allows me to do it → https://stackoverflow.com/a/14731922/6141587

I adapted it to my needs:

const maxWidth = window.innerWidth * 0.9
const maxHeight = window.innerHeight * 0.9
const width = 1366
const height = 768
const ratio = Math.min(maxWidth / width, maxHeight / height)

return {
  width: width * ratio,
  height: height * ratio,
}

Edit: This doesn't work as expected. Jumps up from original width & never returns back to the original width.

Edit 2: That's working as expected I assume. I was resetting my width to width * 0.8 so it never came back to original width otherwise it probably works fine.

However I went with another simpler solution that worked just fine:

const aspectRatio = 16 / 9
const width = window.innerWidth * 0.8
const height = width / aspectRatio

return {
  width,
  height,
}
deadcoder0904
  • 7,232
  • 12
  • 66
  • 163