HTML5 Draggable setDragImage doesn't work with canvas on Chrome

流过昼夜 提交于 2019-12-21 20:44:47

问题


I'm trying to use canvas as my drag image in native HTML5 Drag And Drop API.

The problem is that it works on Firefox but not on Chrome (58) and I can't pinpoint the problem.

Code: https://jsfiddle.net/196urLwd/5/


<div id="thing" draggable="true">DRAG ME</div>

function onDragStart(event){

    var canvas = document.createElement('canvas');
    var context = canvas.getContext('2d');

    canvas.width = 100;
    canvas.height = 20;

    context.fillStyle = '#333333';
    context.fillRect(0, 0, canvas.width, canvas.height);

    context.fillStyle = '#999999';
    context.font = 'bold 13px Arial';
    context.fillText('DRAGGING...', 5, 15);

    event.dataTransfer.setData('text', 'lorem ipsum');
    event.dataTransfer.effectAllowed = 'copy';    
    event.dataTransfer.setDragImage(canvas, -15, 9);

};

var theThing = document.getElementById('thing');
theThing.addEventListener('dragstart', onDragStart, false);

What am I doing wrong?


回答1:


Chrome seems to require the canvas to be in the dom

document.body.append(canvas);

and just hide it with some css

canvas{
  position:absolute;
  left:-100%;
}

https://jsfiddle.net/196urLwd/6/



来源:https://stackoverflow.com/questions/43790022/html5-draggable-setdragimage-doesnt-work-with-canvas-on-chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!