简体   繁体   中英

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

在此处输入图像描述

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

在此处输入图像描述

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

在此处输入图像描述

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>

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM