Search code examples
vue.jsvuetify.jsfabricjsresponsive

How to prevent canvas from overflowing the card and make it responsive in vuetify?


Context:

Hi, I am trying to use fabricjs canvas within vuetify and make it look responsive in all the screens. But currently, I am facing an issue where the canvas is not re-sizing based on card,it overflows the card instead. I have tried using v-responsive but it does not apply the aspect ratio to canvas, could be, the way I am using it is not the right way.

Any suggestions will be helpful.

This is what is happening now

enter image description here

This is what i am trying to achieve

Structure

enter image description here

Mock:

enter image description here

Code

This is what i have tried till now.

<v-layout>
  <v-flex xs12>
    <v-container class="red" fluid>
      <v-layout row wrap align-center justify-center>
        <v-flex xs3 sm3 md3 class="ma-2" class="purple">
          <v-card flat tile class="yellow">
            <v-card-title
              id="fabric-canvas-wrapper"
              class="green pb-0 justify-center"
            >
              <v-responsive aspect-ratio="4/3" class="mx-auto px-3">
                <canvas id="c"> </canvas>
              </v-responsive>
            </v-card-title>

            <v-card-text class="blue text-xs-center py-0">
              <p class=".body-2 pa-2 text-truncate">Kangaroo Valley Safari</p>
            </v-card-text>
          </v-card>
        </v-flex>
      </v-layout>
    </v-container>
  </v-flex>
</v-layout>

https://codepen.io/adatdeltax/pen/OJWOPBo


Solution

  • A canvas element can be sized arbitrarily by a style sheet, its bitmap is then subject to the 'object-fit' CSS property.

    Source

    The width/height of the canvas element are different from the width/height of the canvas element's bitmap. This means that you can use only CSS styles to fix this problem.

    canvas {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    

    Example

    If you want to maintain the aspect ratio you can use the padding trick.

    .canvas-container {
      width: 100%;
      padding-top: 100%; // for 1:1 ratio
    }
    

    Example