1

I use VueJS and I want to incorporate the HTML-Canvas with the Canvas-Context. I'd like to call the context from within my components like:

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

I started in my main.js with:

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

Furthermore, I also don't know how to work with the keyword this in a construct like:

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

So how can I combine the canvas-context and VueJS?

Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58
Timo
  • 119
  • 3
  • 9

1 Answers1

0

One can set the prototype property, just as you are doing, before creating the Vue instances (as is described in Adding Instance Properties).

As is described in this answer, arrow functions don't bind to this, so make sure you use non-arrow functions.

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

See an example of this in the snippet below. Click the draw button to draw a line on the 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

tony19
  • 125,647
  • 18
  • 229
  • 307
Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58