Kenzo
Kenzo

Reputation: 1837

How to trigger mousedown event on fabricjs canvas object?

I have an image object on a canvas fabricJs and i would like to trigger a mousedown(click) event. Here is what i have tried but it seems not to be working a desired.

const canvas = new fabric.Canvas('gameCanvas', {selection: false});
 let myImg;
 
 fabric.Image.fromURL('http://placekitten.com/50/50', function(img) 
 {
   myImg = img.set({
                    left: 50, 
                    top: 50 ,
                    width:50,
                    height:50
                  });
                  
   canvas.add(myImg); 
    
   myImg.on('mousedown', function(e)
   {
      console.log('image click event was simulated at: ', e.clientX, e.clientY);
   
   });
 
 });
 
 document.getElementById('triggerBtn').addEventListener('click', function()
 {
    canvas.trigger('mouse:down', {
          objCanvas: myImg,
          objCanvasX: myImg.left,
          objCanvasY: myImg.top
    });
 });
 
 canvas.on('mouse:down', function(e) {
 
      if(e.objCanvas)
      {
      
        if(e.objCanvas.type === 'image')
        {
            e.objCanvas.trigger('mousedown', {
                   clientX: e.objCanvasX,
                   clientY: e.objCanvasY 
            });
        }
      }
      
      else {
        console.log('image was clicked');
      }
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.0.0/fabric.min.js"></script>
<canvas id="gameCanvas" width="500" height="300" style="border: 2px solid green;"></canvas>
<button id="triggerBtn">Trigger</button>

I found the solution to my problem, please refer to the updated snippets

Upvotes: 2

Views: 1883

Answers (1)

Kenzo
Kenzo

Reputation: 1837

The solution to my question is in the updated snippet

Upvotes: 1

Related Questions