【问题标题】:Responsive canvas vuejs响应式画布 vuejs
【发布时间】:2021-12-15 12:39:07
【问题描述】:

我正在尝试使我的画布适合它的容器,在一个 vue 组件中。 我在挂载时触发 resizeCanvas(),但容器的高度和宽度为 0。 如何拥有适合其容器的画布,以便我可以使用 css 更改容器大小并更新画布? (对不起我的英语,我不流利)

<template lang="html">
  <div class="container" ref="container">
    <canvas ref="canvas" :width="width" :height="height"></canvas>
  </div>
</template>

<script>

export default {
  name: "monster",
  data ()
  {
    return {
      width: 512,
      height: 512
    }
  }
  methods: {
    resizeCanvas(){
      console.log(this.$refs.container.offsetWidth); // logs 0
      this.width = this.$refs.container.offsetWidth
      this.height = this.$refs.container.offsetWidth
    }
  },
  mounted ()
  {
    console.log(this.$refs.container.offsetWidth) // logs 0
    window.addEventListener("resize", this.resizeCanvas);
    this.resizeCanvas()  
  },
  unmounted() {
    window.removeEventListener("resize", this.resizeCanvas);
  },
}
</script>

<style lang="css" scoped>
.container {
  width: 100%; height: 100%
}
</style>

【问题讨论】:

    标签: javascript css vue.js html5-canvas


    【解决方案1】:

    VueJS 中的挂载生命周期钩子并不能保证 DOM 已准备就绪:您需要等待 this.$nextTick(),然后检查容器元素的尺寸。

    你可以把逻辑移到nextTick的回调中,即:

    mounted () {
        this.$nextTick(() => {
            console.log(this.$refs.container.offsetWidth);
            window.addEventListener("resize", this.resizeCanvas);
            this.resizeCanvas();
        });
    },
    

    如果你熟悉 async/await 的做事方式,那么你也可以这样做:

    async mounted () {
        await this.$nextTick();
    
        console.log(this.$refs.container.offsetWidth);
        window.addEventListener("resize", this.resizeCanvas);
        this.resizeCanvas();
    },
    

    另一种可能性是将这个“等待 DOM 准备好”的职责委托给 resizeCanvas 函数,这样您就可以完全抽象和分离关注点:

    methods: {
        async resizeCanvas(){
          await this.$nextTick();
          
          this.width = this.$refs.container.offsetWidth
          this.height = this.$refs.container.offsetWidth
        }
    },
    mounted () {
        window.addEventListener("resize", this.resizeCanvas);
        this.resizeCanvas();
    },
    

    【讨论】:

    • 它不起作用:/console.log 仍然记录 0
    • @ValentinRegnault 那么请分享minimal reproducible example。根据您分享的内容,我不明白为什么没有返回预期的尺寸。
    • 好的,我尝试了一个空白应用程序,它运行良好。但是在我的离子项目中它没有。因此,我将关闭此部分,并可能更精确地重新打开另一个部分。谢谢!
    猜你喜欢
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-20
    • 2014-12-03
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    相关资源
    最近更新 更多