【问题标题】:How can VueJS + Canvas-Context be linked together?VueJS + Canvas-Context 怎么联系在一起?
【发布时间】:2017-07-07 12:58:28
【问题描述】:

我使用 VueJS,我想将 HTML-CanvasCanvas-Context 合并。我想在我的components 中拨打context,例如:

mounted() {
  this.$c.moveTo(100, 100)
  this.$c.lineTo(200, 200)
}

我从main.js 开始:

Vue.prototype.$c = document.querySelector('canvas').getContext('2d')

此外,我也不知道如何在以下构造中使用关键字this

const Something = (x, y) => {
  this.x = x
  this.y = y
  this.draw() {
    this.$c.moveTo(100, 100)
    this.$c.lineTo(200, 200)
  }
}

那么我该如何组合canvas-contextVueJS

【问题讨论】:

    标签: javascript html canvas vue.js this


    【解决方案1】:

    可以在创建 Vue 实例之前设置原型属性,就像您正在做的那样(如 Adding Instance Properties 中所述)。

    this answer 中所述,箭头函数不会绑定到this,因此请确保使用非箭头函数。

    不要在实例属性或回调上使用arrow functions(例如vm.$watch('a', newVal => this.myMethod()))。由于箭头函数绑定到父上下文,this 不会像您期望的那样成为 Vue 实例,this.myMethod 将是 undefined1

    请参阅下面的 sn-p 中的示例。点击draw按钮在画布上画一条线。

    //wait for DOM to load
    document.addEventListener('DOMContentLoaded', function() {
      //set property on all Vue instances
      Vue.prototype.$c = document.getElementById('myCanvas').getContext('2d');
      //create Vue instance
      var vm = new Vue({
        el: '#example',
        methods: {
          draw: function() {
            this.$c.beginPath();
            this.$c.moveTo(100, 100);
            this.$c.lineTo(200, 200);
            this.$c.stroke();
          }
        }
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
    <canvas id="myCanvas"></canvas>
    <div id="example">
      <button @click="draw">draw</button>
    </div>

    1https://vuejs.org/v2/guide/instance.html#Properties-and-Methods

    【讨论】:

      猜你喜欢
      • 2020-04-15
      • 2021-05-28
      • 2021-03-09
      • 1970-01-01
      • 2021-07-19
      • 1970-01-01
      • 1970-01-01
      • 2012-08-09
      • 1970-01-01
      相关资源
      最近更新 更多