javascript - VueJS + Canvas-Context 如何链接在一起?

标签 javascript html canvas vue.js this

我使用VueJS,我想将HTML-CanvasCanvas-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 结合起来?

最佳答案

可以像您一样在创建 Vue 实例之前设置原型(prototype)属性(如 Adding Instance Properties 中所述)。

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

Don’t use arrow functions on an instance property or callback (e.g. vm.$watch('a', newVal => this.myMethod())). As arrow functions are bound to the parent context, this will not be the Vue instance as you’d expect and this.myMethod will be undefined. 1

请参阅下面的代码片段中的示例。单击绘制按钮在 Canvas 上绘制一条线。

//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://v2.vuejs.org/v2/guide/instance.html#Properties-and-Methods

关于javascript - VueJS + Canvas-Context 如何链接在一起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44971399/

相关文章:

html - Swiffy 转换错误(Flash 到 HTML5)

javascript - Canvas 使用带 Angular 线性渐变背景集

javascript - masonry 留空间隙

javascript - Canvas 上漂亮的椭圆?

javascript - 以不可变的方式过滤作为对象属性的数组

javascript - 在 try-catch block 内的 HTML 文件中导入 JavaScript 文件

javascript - 如果弹出 div 的位置设置为相对,则表行大小增加

javascript - 如何根据 ID 列表查询 RethinkDB

Javascript scrollTop 错误

html5 canvas 应用程序中的 JavaScript base64 图像源内存管理