Search code examples
javascripthtmldrag-and-dropdraggable

HTML5 setDragImage(): dragIcon.width does absolutely nothing


When using the HTML5 drag and drop API, it would appears though the .width property on has no impact on the width of an image being used as an icon for dragging. Take this fiddle for example: http://jsfiddle.net/cnAHv/7/. You can set dragIcon.width to anything you want, and it will not change the actual width of the icon.

Most of the resources on the web seem to arbitrarily set dragIcon.width to 100. Is this just a matter of people copying eachother's code without checking functionality?

So...

  1. Is the width property on an image variable actually something that setDragImage() will accept?
  2. If not, how would you set the width of the icon without manually changing sizing the image in a program like photoshop?

Solution

  • When you use an <img> in setDragImage Javascript will just use the actual image bitmap data, ignoring other attributes like width. Check the specs.

    However if you do something like this:

    function handleDragStart(e) {
        var dragIcon = document.createElement('img');
        dragIcon.src = 'http://jsfiddle.net/favicon.png';
        dragIcon.width = '100';
        var div = document.createElement('div');
        div.appendChild(dragIcon);
        document.querySelector('body').appendChild(div);
        e.dataTransfer.setDragImage(div, -10, -10);
    }
    

    http://jsfiddle.net/cnAHv/9/

    You will see the drag shadow now contains the bigger image. It occurs because when we use other visible HTML elements (that's why I appended the DIV to the body), the browser will use its rendered view as a drag image.