How to draw onto a canvas with Vue.js and JavaScript?

Sometimes, we want to draw onto a canvas with Vue.js and JavaScript.

In this article, we’ll look at how to draw onto a canvas with Vue.js and JavaScript.

How to draw onto a canvas with Vue.js and JavaScript?

To draw onto a canvas with Vue.js and JavaScript, we can get the canvas with refs and then draw on it with fillText.

For instance, we write:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>

<div id='app'>

</div>

to add the Vue script and app container.

Then we write:

const v = new Vue({
  el: '#app',
  template: `<canvas ref='canvas' style='width: 200px; height: 200px'></canvas>`,
  data: {
    'exampleContent': 'hello'
  },
  methods: {
    updateCanvas() {
      const {
        canvas
      } = this.$refs
      ctx = canvas.getContext('2d');
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.fillStyle = "black";
      ctx.font = "20px Georgia";
      ctx.fillText(this.exampleContent, 10, 50);
    }
  },
  mounted() {
    this.updateCanvas();
  }
});

We add the canvas element into the template.

Then we set the exampleContent property to 'hello'.

Next, we add the updateCanvas method that gets the canvas from this.$refs.

Then we get the context with getContext.

Next, we call clearReact to clear its contents.

Then we set the fillStyle and font to set the fill and font style of the text.

And then we call fillText with this.exampleContent and coordinates to write text into the canvas.

Finally, we call this.updateCanvas in the mounted to write the text with the canvas is loaded.

Conclusion

To draw onto a canvas with Vue.js and JavaScript, we can get the canvas with refs and then draw on it with fillText.