我使用VueJS,我想将HTML-Canvas
与Canvas-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-context
和 VueJS
结合起来?
最佳答案
可以像您一样在创建 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 andthis.myMethod
will beundefined
. 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/