Bill Mills
Bill Mills

Reputation: 421

Unexpected HTML5 drag & drop ghost image behaviour

I've spent the day on a funny problem - I have some canvases that I'd like to drag around using native HTML5 drag and drop functionality. Everything works great, except I eventually found that in Chrome 28.0.1500.95, the default ghost image of the canvas doesn't appear if the canvas is the child of an inline-block div. Check out this minimal working example:

<html>
    <body>
        <div style='display:inline-block'> 
            <canvas id='canvas1' width='100px' height='100px' draggable='true'></canvas>
        </div>

        <div> 
            <canvas id='canvas2' width='100px' height='100px' draggable='true'></canvas>
        </div>

        <script type="text/JavaScript">
            var canvas1, canvas2, context1, context2;

            canvas1 = document.getElementById('canvas1');
            context1 = canvas1.getContext('2d');

            canvas2 = document.getElementById('canvas2');
            context2 = canvas2.getContext('2d');

            context1.fillText('no drag', 10, 30);
            context2.fillText('yes drag', 10, 30);
        </script>
    </body>
</html>

A ghost image appears when I try to drag 'yes drag', but not for 'no drag'. However, if I also stick in a drop target, I can trigger it by dropping 'no drag' on it as per normal, despite the absent ghost. I'd like to understand why the ghost image disappears apparently based on the CSS of the parent, or if there's something else going on here - thanks in advance!

Upvotes: 6

Views: 2787

Answers (1)

nmaier
nmaier

Reputation: 33162

This might be just a bug in Chrome (seems to work in Firefox, once you actually .setData())

If you're just looking for an easy, albeit somewhat nasty work-around: .setDragImage() explicitly, based on the canvas.

function dragstart(e) {
    var di = new Image();
    di.src = this.toDataURL("image/png");
    e.dataTransfer.setDragImage(di, 10, 10);
    // Run in firefox
    e.dataTransfer.setData("text/plain", this.id);
}

Fiddle (you might want to fiddle with the position of the image a bit).

Upvotes: 0

Related Questions