Search code examples
javascripthtmlgoogle-chromedrag-and-drophtml5-draggable

setDragImage not removing ghost image on Chrome?


I have an element that is draggable. I want to remove the ghost image, since I will be creating that in another way.

However, Google Chrome is not letting me stop the ghost image from appearing using setDragImage(). The blank image is being created before the drag, and I'm using setDragImage() inside the dragstart event handler, so I don't see what I'm doing wrong. The ghost image should not be appearing.

Here's an example:

const blankCanvas = document.createElement('canvas');

document.querySelector('.item')
  .addEventListener('dragstart', (e) => {
    e.dataTransfer.setDragImage(blankCanvas, 0, 0);
  });
.item {
  display: inline-block;
  width: 5rem;
  height: 5rem;
  overflow: hidden;
  margin: 1rem;
  border: 2px solid #fe0000;
  cursor: pointer;
}

.item__img {
  width: 100%;
  height: auto;
}
<div draggable="true" class="item">
  <img src="https://i.sstatic.net/drhx7.png" alt="" class="item__img">
</div>

On Chrome, If you drag the box with the red border, the ghost image will appear, even though I'm using setDragImage(). Everything works correctly on Firefox (and Edge... doesn't even have the function).

My Chrome version is 66.


Solution

  • The problem is coming from the image. If you try dragging the red border, it will work correctly. The problem will appear only when the drag begins on the image inside the draggable element. Maybe Chrome has some special treatment for images; I don't know.

    You can mitigate this by disabling pointer events on the image:

    .item img {
      pointer-events: none;
    }
    

    Here is a working example:

    const blankCanvas = document.createElement('canvas');
    
    document.querySelector('.item')
      .addEventListener('dragstart', (e) => {
        e.dataTransfer.setDragImage(blankCanvas, 0, 0);
      });
    .item {
      display: inline-block;
      width: 5rem;
      height: 5rem;
      overflow: hidden;
      margin: 1rem;
      border: 2px solid #fe0000;
      cursor: pointer;
    }
    
    .item__img {
      width: 100%;
      height: auto;
      
      /* The fix */
      pointer-events: none;
    }
    <div draggable="true" class="item">
      <img src="https://i.sstatic.net/drhx7.png" alt="" class="item__img">
    </div>