2

我正在实现从缩略图中拖动图像并放入画布中并绘制它。

我在事件 ondragstart 期间使用了 datatransfer.setdata(),在事件 ondrop 期间使用了 datatransfer.getdata()。它在 Firefox 中运行良好,但在 chrome 中无法运行。我知道在 chrome 中不支持数据传输。那么,什么可以是一个好的解决方案,也应该是跨浏览器兼容的!

function dragIt(event) {
event.dataTransfer.setData("URL", event.target.id)
};

function dropIt(event) {
  var theData = new Image();
  theData = event.dataTransfer.getData("URL");
  dt = document.getElementById(theData);
  event.preventDefault();
  var ctx = this.getContext('2d');
  ctx.clearRect(0,0,this.width,this.height);
  ctx.drawImage(dt, 0, 0);      
};

var out = document.getElementById('out');
        var Can1 = document.createElement("canvas");
        Can1.height="100";
        Can1.width="100";
        Can1.style.cssText = 'position:relative; top:5px;left:500px;border:2px  solid black;'  
        Can1.ondragover = function(event) {
        event.preventDefault();
        };
        Can1.ondrop = dropIt;  
        out.appendChild(Can1);
4

1 回答 1

1

I know the proverbial horse has probably bolted on this question but I've also just noticed this problem in Chrome with getData/setData. For me, it works only if you use "text" or "text/plain" as the format for the data, and everything else fails with event.dataTransfer.getData(format) returning undefined.

In Chrome's Developer Tools, you can inspect the event.dataTransfer.types property to see which values are accepted for the "format" parameter to the getData/setData functions.

Therefore changing "URL" to "text" may solve the problem in this case. Unfortunately, I've so far failed to find any information on why Chrome's chosen to implement only these formats.

于 2014-02-24T18:12:03.367 回答