问题描述
我想根据其父容器的宽度设置Konva的高度和宽度。当我在舞台上使用静态值时,
stageConfiguration:{ height: innerWidth * .5,width:innerWidth * 0.5}
每次我调整屏幕大小时都必须刷新。有没有一种方法可以将动态高度和宽度设置为 stageConfiguration 。当前,我一直坚持这一观点,并在寻找一种设置动态高度和宽度的方法。
<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>
解决方法
您可以在窗口中使用ResizeObserver
或resize
事件来检测大小变化。
这是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>
演示:https://codesandbox.io/s/vue-konva-change-stage-size-or-resize-tbwec?file=/src/App.vue