0
votes

I want to set the height and width of the Konva based on the width of its parent container. As I was using static value for the stage which is

stageConfiguration:{ height: innerWidth * .5, width:innerWidth * 0.5}

And have to refresh every time I resize the screen. Is there a way to set the dynamic height and width to stageConfiguration. Current I am stuck on this and looking for a way to set dynamic height and width.

<template>
<div class="konvaContainer">
   <v-stage :config="stageConfiguration" >
      <v-layer>
             
      </v-layer>
   </v-stage>
</div>
</template>
<script>
export default {
  components: {
    Loading
  },
  data: () => ({
    stageConfiguration: {}
  )},
  methods:
  {
    responsiveStage : function() {
    var container = document.querySelector('.konvaContainer');
    var width = container.clientWidth;
    const stageWidth= width*.5;
    const stageHeight= width *.5;
    this.stageConfiguration ={
      width:stageWidth,
      height:stageHeight
    }
  }}
}
</script>
1

1 Answers

0
votes

You can use ResizeObserver or resize event from the window to detect size changes.

Here is a solution with ResizeObserver:

<template>
  <div class="container">
    <v-stage ref="stage" :config="stageSize">
      <v-layer>
        <v-circle
          :config="{
            x: stageSize.width / 2,
            y: stageSize.height / 2,
            radius: stageSize.width / 2,
            fill: 'green',
          }"
        />
      </v-layer>
    </v-stage>
  </div>
</template>

<style>
.container {
  width: 100vw;
  height: 100vh;
}
</style>
<script>
export default {
  data() {
    return {
      stageSize: {
        width: 10,
        height: 10,
      },
    };
  },
  mounted() {
    const container = document.querySelector(".container");
    const observer = new ResizeObserver(() => {
      this.stageSize.width = container.offsetWidth;
      this.stageSize.height = container.offsetHeight;
    });
    observer.observe(container);
  },
};
</script>

Demo: https://codesandbox.io/s/vue-konva-change-stage-size-or-resize-tbwec?file=/src/App.vue