I am implementing dragging an image from thumbnail and dropping into a canvas and draw it.
I have used datatransfer.setdata()
during the event ondragstart
and datatransfer.getdata()
on event ondrop
. It is working perfectly in Firefox, but doesn’t work in Chrome. I have come to know that in Chrome datatransfer is not supported. So, what can be a good solution, that should be cross browser compatible too!
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);
2
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.
2