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"
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.
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; };
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With