When a drag occurs, a translucent image is generated from the drag target (the element the dragstart
event is fired at), and follows the mouse pointer during the drag. This image is created automatically, so you do not need to create it yourself. However, if a custom image is desired, the DataTransfer.setDragImage()
method can be used to set the custom image to be used. The image will typically be an <img>
element but it can also be a <canvas>
or any other visible element.
The method's x
and y
coordinates define how the image should appear relative to the mouse pointer. These coordinates define the offset into the image where the mouse cursor should be. For instance, to display the image so that the pointer is at its center, use values that are half the width and height of the image.
This method must be called in the dragstart
event handler.
setDragImage(imgElement, xOffset, yOffset)
This example shows how to use the setDragImage()
method. Note the example refers to an image file named example.gif
. If that file is present, it will be used as the drag image and if that file is not present, the browser will use its default drag image.
demo
<!doctype html>
<html lang="en">
<head>
<title>Example of DataTransfer.setDragImage()</title>
<meta name="viewport" content="width=device-width" />
<style>
div {
margin: 0em;
padding: 2em;
}
#source {
color: blue;
border: 1px solid black;
}
#target {
border: 1px solid black;
}
</style>
<script>
function dragStartHandler(ev) {
console.log("dragStart");
ev.dataTransfer.setData("text/plain", ev.target.id);
const img = new Image();
img.src = "example.gif";
ev.dataTransfer.setDragImage(img, 10, 10);
}
function dragOverHandler(ev) {
console.log("dragOver");
ev.preventDefault();
}
function dropHandler(ev) {
console.log("Drop");
ev.preventDefault();
const data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>
<h1>Example of <code>DataTransfer.setDragImage()</code></h1>
<div>
<p id="source" ondragstart="dragStartHandler(event);" draggable="true">
Select this element, drag it to the Drop Zone and then release the
selection to move the element.
</p>
</div>
<div
id="target"
ondrop="dropHandler(event);"
ondragover="dragOverHandler(event);">
Drop Zone
</div>
</body>
</html>