Escoute
Escoute

Reputation: 396

unable to move fabricjs object

var canvas = new fabric.Canvas('canvas');
canvas.selection = false;
var circle = new fabric.Circle({
    left: 150,
    top: 150,
    radius: 50,
    originX: 'center',
    originY: 'center',
    selectable: false
});
canvas.add(circle);
circle.on('mousedown',function(){
 console.log('down')
 circle.set({
  selectable: true
 })
 canvas.renderAll();
})
circle.on('mouseout',function(){
 console.log('out')
  circle.set({
  selectable: false
 })
 canvas.renderAll();
})
canvas {
  border: 2px dotted green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.16/fabric.min.js" charset="utf-8"></script>
<canvas id="canvas" width="400" height="400"></canvas>

I want to make object selectable on mouse down, and on mouse out i want to make not selectable. If I click inside and dragging its not moving. But if i click inside more than two times, its working. But I want to make this work clicking once. How to achieve the same?

--Update--

As suggested by @AndreaBogazzi, it will work for mouesmove in desktop, but the same won't work for touch devices as only touch start will work if I touch on object.

Upvotes: 1

Views: 3370

Answers (2)

AndreaBogazzi
AndreaBogazzi

Reputation: 14731

This can't be done in fabricjs. The mouse down event is fired AFTER The selection logic is already executed.

What you can do is making it selectable on mouseover

If this works for you, it would equal to an object to be always selectable unless you are running custom logic in your mousedown ( or mouseover ) event to make it selectable under some circumstances.

var canvas = new fabric.Canvas('canvas');
canvas.selection = false;
var circle = new fabric.Circle({
    left: 150,
    top: 150,
    radius: 50,
    originX: 'center',
    originY: 'center',
    selectable: false
});
canvas.add(circle);
circle.on('mouseover',function(){
 console.log('over')
 circle.set({
  selectable: true
 })
 canvas.renderAll();
})
circle.on('mouseout',function(){
 console.log('out')
  circle.set({
  selectable: false
 })
 canvas.renderAll();
})
canvas {
  border: 2px dotted green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.16/fabric.min.js" charset="utf-8"></script>
<canvas id="canvas" width="400" height="400"></canvas>

Upvotes: 1

Vanojx1
Vanojx1

Reputation: 5574

Just remove controls and borders to make it only draggable

var canvas = new fabric.Canvas('canvas');
canvas.selection = false;
var circle = new fabric.Circle({
  left: 150,
  top: 150,
  radius: 50,
  originX: 'center',
  originY: 'center',
  selectable: true,
  hasControls: false,
  hasBorders: false
});
canvas.add(circle);
canvas {
  border: 2px dotted green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.16/fabric.min.js" charset="utf-8"></script>
<canvas id="canvas" width="400" height="400"></canvas>

Upvotes: 2

Related Questions