sailormoon
sailormoon

Reputation: 335

How to clear canvas in Vue?

I have to clear my canvas on click at button. I think I tried every way to clean it, which I found on the internet. I clear my canvas, but when I start to draw again (on clear canvas), the previous drawing is coming back. I'll show you this in steps below.

STEP 1: first drawing

enter image description here

STEP 2: clearing the canvas by clicking on button with function clear (please check below in my code). Result: canvas is clear.

enter image description here

STEP 3: I start to draw on clear canvas, but when mouse-up, a new drawing appears with the old one.

enter image description here

I don't want this old "ghost" drawing, I want to clear it, I need fully clear canvas to draw completely new drawing. Can anyone help me? Thanks in advance.

CODE:

Play.vue

<template>
  <div class="play">
    <Canvas/>    
  </div>
</template>

<script>
export default {
  name: "play",
  components: {
    Canvas
  }
}
</script>

Canvas.vue

<template>
  <div class="main">
    <canvas id="canvas"></canvas>
    <button v-on:click="clear">clear</button>
  </div>
</template>

<script>
import { fabric } from "fabric";

export default {
  name: "Canvas",
  data: () => ({
    canvas: null
  }),
  methods: {
    clear: function () {
      var ctx = this.canvas.getContext("2d");
      ctx.beginPath();
      ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
    }
  },
  mounted() {
    this.canvas = new fabric.Canvas("canvas");
    ...
  }
}
</script>

Upvotes: 0

Views: 1503

Answers (1)

Steven B.
Steven B.

Reputation: 9372

You need to use .clear() on the instance of the fabric canvas

    clear: function () {
      this.canvas.clear();
    }

Upvotes: 1

Related Questions