skip to Main Content

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?

2

Answers


  1. 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.

    Login or Signup to reply.
  2. This answer might be a bit late but you can also use a canvas to scale your original image.

    function handleDragStart(e) {
        var dragIcon = document.createElement('img');
        dragIcon.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD///+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4Ug9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC';
        var width = 100;
        var height = width * (3/4); // The height must be set explicitly. I'm assuming the image is 4:3 for this example
        var c = document.createElement("canvas");
        c.width = width;
        c.height = height;
        var ctx = c.getContext('2d');
        ctx.drawImage(dragIcon,0,0,width,height);
        dragIcon.src = c.toDataURL();
        e.dataTransfer.setDragImage(dragIcon, -10, -10);
    }
    

    http://jsfiddle.net/cnAHv/138/

    The only downside to this is that the canvas may be tainted if the image doesn’t come from the same origin. More on tainted canvases here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search