Spark
Spark

Reputation: 2487

Event handler for object selection on fabricjs canvas

I have a canvas that has some elements and i would like to add an event handler when the user selects an element(clicks on an element) on the canvas.

I tried using selection: created and object: selected events to handle the same but It only works when a user selects an element and then clicks on somewhere else in the canvas and then tries to select another element it works perfectly, But When the user clicks on one element(event handler triggered) and then clicks on another element the event handler is not triggering. How do I handle this?

i see that there is an option to use as mentioned here in the issue with selection:created and selection:updated https://github.com/fabricjs/fabric.js/issues/4886

But is there a way i could use them together ?

const canvas = new fabric.Canvas('paper', {
  preserveObjectStacking: true,
  enableRetinaScaling: false,
  imageSmoothingEnabled: false
});
canvas.setHeight(500);
canvas.setWidth(700);


const red = new fabric.Rect({
	id: 'red',
  left: 10,
  top: 10,
  width: 100,
  height: 100,
  fill: 'red'
});

const green = new fabric.Rect({
	id: 'green',
  left: 150,
  top: 150,
  width: 100,
  height: 100,
  fill: 'green'
});

canvas.add(red);
canvas.add(green);

canvas.renderAll();

canvas.on("selection:created", function(obj){
	alert(obj.target.id)
});
canvas.on("selection:updated", function(obj){
	alert(obj.target.id)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.2.3/fabric.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<canvas id="paper" width="400" height="400" style="border:1px solid #ccc"></canvas>

Upvotes: 8

Views: 12800

Answers (1)

Spark
Spark

Reputation: 2487

Here is a pretty simple solution for having both the event handlers combined and linking both of them to the same method will be a simple solution for this, Any better solutions will be appreciated.

canvas.on({
  'selection:updated': HandleElement,
  'selection:created': HandleElement
});

function HandleElement(obj){
   //Handle the object here 
}

Upvotes: 16

Related Questions