4

Apparently you can use and image element or a canvas element with HTML5's native drag and drop setDragImage(). This overrides the native 'ghosted' image of what you're dragging.

However I can't seem to get it to work, does anyone know what I'm missing?

var canvas              = document.createElement('canvas');
    context             = canvas.getContext('2d');
    context.height      = '100px';
    context.width       = '200px';
    context.fillStyle   = 'blue';
    context.font        = 'bold 16px Arial';
    context.fillText('hello world', 0, 16);
    context.fillRect(20, 10, 200, 100);

    console.log(canvas);
e.dataTransfer.setDragImage( canvas, 50,50 );

Also, I'm very surprised that I cannot use a div with createElement() I guess the div must already exist to use that as the drag image?

var dragIcon = document.createElement('div');
    dragIcon.style.cssText = 'width:200px;height:100px;background-color:red;';
Ben Racicot
  • 5,332
  • 12
  • 66
  • 130
  • 3
    For the first part of the question, canvas's context2d has no width nor height properties, you should set the canvas' one. But this should still work with your given code : https://jsfiddle.net/45k8z4kr/1/ At least it does in FF... There seems to be a bug in chrome, where you need to pass the dataURL as src of an image element : https://jsfiddle.net/76Lc1tas/ – Kaiido Dec 29 '15 at 02:39
  • 1
    For the second part, the [specs](https://html.spec.whatwg.org/multipage/interaction.html#dom-datatransfer-setdragimage) say that if the element argument is not an image, "set the drag data store bitmap to an image generated from the given element". Which will produce nothing for a non visible element. (Older specs were more clear and stated "image should be a visible node and the drag image will be created from this.") – Kaiido Dec 29 '15 at 02:39

1 Answers1

0

The Canvas element needs to be part of the DOM for some reason as mentioned in this answer link.

Apply styling to the canvas so that it is not visible to the user. One way of doing so which would work for most use cases is

canvas.style.position = 'absolute';
canvas.style.left = '-100%';
canvas.style.zIndex = '-100';

Then append the Canvas element to the DOM.

document.body.append(canvas);
Sameer Basil
  • 366
  • 5
  • 11