1

How can I create a custom ghost image for my draggable element based on the html-code of that element?

For example, let's say you want to manually create the default ghost image. You could use the html-code of the draggable element to construct the ghost image. But I think I'm missing something here (see code below). Any idea what?

draggable.addEventListener('dragstart', event => {
  const draggedEl = event.target

      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      
      const data =
      "data:image/svg+xml;utf8," +
      encodeURIComponent(
        "<svg xmlns='http://www.w3.org/2000/svg' width='200' height='200'>" +
          "<foreignObject width='100%' height='100%'>" +
            "<div xmlns='http://www.w3.org/1999/xhtml' style='font-size:40px'>" +
              "<div xmlns='http://www.w3.org/1999/xhtml'>" + 
                draggedEl.outerHTML + 
              "</div>" +
            "</div>" +
          "</foreignObject>" +
        "</svg>"
      )


            
      const img = new Image()
      img.src = data
      img.style.zIndex = 1

      img.onload = function() {
        ctx.drawImage(img, 0, 0)
      }
      
      event.dataTransfer.setDragImage(img, 0, 0)
})

I would like to not use any libraries for this implementation.

Edit: Sometimes the custom ghost image does show. It's, however, very unreliable.

  • You are drawing the image on the canvas when the image load, which is after your code runs to completion, and thus, after you set the drag-image. At the time you call `setDragImage`, your canvas is empty. – Kaiido Jul 08 '22 at 11:47

1 Answers1

0

I ended up implementing the dragging behaviour of the element from scratch -- and thus overriding the default behaviour -- instead of trying to set a custom ghost image with event.dataTransfer.setDragImage(img, 0, 0).

For example see this Stack Overflow post: Style drag ghost element

However, any help understanding why the original code doesn't work is still appreciated.