deadcoder0904
deadcoder0904

Reputation: 8693

Make a responsive rectangle in Konva (React Konva) that maintains aspect ratio

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.

Upvotes: 0

Views: 924

Answers (1)

deadcoder0904
deadcoder0904

Reputation: 8693

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,
}

Upvotes: 1

Related Questions