Crypto
Crypto

Reputation: 157

Button click event fires with every event in fabricjs

I have a problem with events on a fabricjs canvas for two days. I guess it's about fabricjs. I found problem but i could not understand why it is a problem.

I have a mouse event and two button (click event) that call functions clip1 and clip2.

  1. Mouse event works normally until i call clip1 via button1.
  2. After just one call to clip1, it works with every down event.
  3. No problem with clip2 function that is called via button2.

Difference between clip1 and clip2: clip1 use this.canvas and clip2 creates a new canvas. Seems like button1 click event register itself to all events of canvas. Like a bug, huh?

.HTML

<canvas id="c" width="800" height="800" style="border:1px solid #000"></canvas>
<img src="../../clips/kupurFirst.jpg" id="my-image1" hidden>
<button (click)="clip1()">Clip1 </button>
<button (click)="clip2()">Clip2</button>

.TS

import { Component, OnInit } from '@angular/core';

@Component({
  moduleId: module.id,
  selector: 'app-fabric',
  templateUrl: 'fabric.component.html',
  styleUrls: ['fabric.component.css']
})
export class FabricComponent implements OnInit {

  public canvas: any;
  public src: string;

  constructor() { }

  ngOnInit() {

    this.canvas = new fabric.Canvas('c');
    this.src = "../../clips/kupurSecond.jpg";

    loadCanvas(this.src, this.canvas);

    // Works normally until click event (clip1) fires
    this.canvas.on('mouse:down', function (event) {
      console.log("Down");
    });
  }

  // Problem with this.canvas
  public clip1() {
    loadCanvas(this.src, this.canvas);
    this.canvas.clipTo = function (ctx) {
      console.log("clip1");
    };
  }
  // No problem with new canvas element
  public clip2() {
    var canvas = new fabric.Canvas('c');
    loadCanvas(this.src, canvas);

    canvas.clipTo = (ctx) => {
      console.log("clip2");
    };
  }

}

var loadCanvas = (src: string, canvas: any) => {
  fabric.Image.fromURL(src, (oImg) => {
    canvas.add(oImg);
  }, { hasControls: false, selectable: false, evented: false, strokeDashArray: [2, 2], opacity: 1 });

}

Upvotes: 1

Views: 1214

Answers (1)

Crypto
Crypto

Reputation: 157

I found a solution. Does not seems perfect but works for me:

this.canvas.clipTo = null; // Prevents fire of clipTo function at every event.

I put this line into a new button (function) and named it as "undo".

Upvotes: 1

Related Questions