Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide ghost image in reactjs drag event?

I'm using onDrag method in react js. I want to happen drag while i'm dragging the image, but I don't want to show the ghost image. I used css "-webkit-user-drag:none", but it is completely prevent the drag functionality. I want both to work in same time.

Sample code,

<img
                    style={{ left: `${pixels}px` }}
                    onDrag={this.dragOn.bind('start')}
                    onDragEnd={this.dragOn.bind(this, 'end')}
                    alt=""
                    height="20"
                    width="15"
                    draggable="true"
like image 202
Sathya Avatar asked Aug 16 '17 07:08

Sathya


People also ask

How do you stop ghost dragging?

In the above example, when the image is clicked and dragged, it creates a draggable ghost image that follows the cursor. To prevent dragging of this ghost image, the draggable attribute is used. On setting this attribute for that image element to “false”, its dragging is prevented.

How do I stop my pictures from dragging?

One way to disable dragging an image from an HTML page is to set the ondragstart property of an image element to a function that returns false . return false; };


2 Answers

First create a small transparent image in componentDidMount:

componentDidMount() {
  this.dragImg = new Image(0,0);
  this.dragImg.src =
  'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
}

Then in your handler for onDragStart:

handleOnDragStart = e => {
  e.dataTransfer.setDragImage(this.dragImg, 0, 0);
}

Note: You have to call the setDragImage method in the onDragStart handler. It won't work in the method used for onDrag.

like image 90
Paul Freeman Avatar answered Oct 04 '22 13:10

Paul Freeman


In the documentation for the html5 drag-and-drop standard here: https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Drag_operations#dragfeedback

you can see how to change this translucent image it appears under the cursor. You can set to something more discrete image (or canvas) or even to a blank image like a new Image()

event.dataTransfer.setDragImage(new Image(), 0, 0);

but I would advise against using a blank image since you need some sort of visual cue for the drag-and-drop.

like image 32
vassiliskrikonis Avatar answered Oct 04 '22 12:10

vassiliskrikonis