vinkovsky
vinkovsky

Reputation: 310

How to simulate mouse up event fabric js

I am developing a project where I need to simulate a mouseup event. This should work like this:

I click on the canvas to draw or drag objects, and after timeout I want to handle the mouseup event. How can I achieve this?

My codepen example

Thank you

var canvas = this.__canvas = new fabric.Canvas('c');
  
canvas.add(new fabric.Rect({ top: 100, left: 100, width: 50, height: 50, fill: '#f55' }),
            new fabric.Circle({ top: 140, left: 130, radius: 75, fill: 'green' }),
            new fabric.Triangle({ top: 100, left: 110, width: 100, height: 100, fill: 'blue' }))

document.addEventListener('keydown', (e) => {

  if (e.code == 'AltLeft') {
    canvas.isDrawingMode = !canvas.isDrawingMode;
  }
});

setTimeout(()=> {
  console.log('Must handle mouseup event here')
},5000)
canvas {
  border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.1/fabric.min.js"> </script>

<canvas id="c" width="300" height="300"></canvas>

Upvotes: 0

Views: 1365

Answers (1)

AndreaBogazzi
AndreaBogazzi

Reputation: 14731

Creating a programmatic mouse event is described here: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent

Generate an event of type mouseup and then dispatch it on the canvas upper layer that you can reach using the canvas.upperCanvasEl.

var canvas = this.__canvas = new fabric.Canvas('c');
  
canvas.add(new fabric.Rect({ top: 100, left: 100, width: 50, height: 50, fill: '#f55' }),
            new fabric.Circle({ top: 140, left: 130, radius: 75, fill: 'green' }),
            new fabric.Triangle({ top: 100, left: 110, width: 100, height: 100, fill: 'blue' }))

document.addEventListener('keydown', (e) => {

  if (e.code == 'AltLeft') {
    canvas.isDrawingMode = !canvas.isDrawingMode;
  }
});

setTimeout(()=> {
  console.log('Must handle mouseup event here');
  var evt = new MouseEvent("mouseup", {
    bubbles: true,
    cancelable: true,
    view: window
  });
  canvas.upperCanvasEl.dispatchEvent(evt);
},5000)
canvas {
  border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.1/fabric.min.js"> </script>

<canvas id="c" width="300" height="300"></canvas>

Upvotes: 5

Related Questions