Created
August 6, 2018 07:10
-
-
Save oscarotero/f1026a208a91bbcf089f609844ad5723 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Drag test</title> | |
<style> | |
#zone { | |
position: relative; | |
background: yellow; | |
height: 800px; | |
} | |
img { | |
position: absolute; | |
} | |
</style> | |
</head> | |
<body> | |
<div id="zone"> | |
<img draggable src="http://placehold.it/200x200"> | |
</div> | |
<script> | |
const grid = 200; | |
let dragging; | |
const zone = document.getElementById('zone'); | |
zone.addEventListener('dragstart', ev => { | |
const target = ev.target; | |
if (target && target.nodeName === 'IMG') { | |
dragging = target; | |
console.log(ev.type, ev); | |
const position = { | |
left: ev.offsetX, | |
top: ev.offsetY | |
}; | |
ev.dataTransfer.dropEffect = 'copy'; | |
ev.dataTransfer.setData('text/plain', JSON.stringify(position)); | |
} | |
}); | |
zone.addEventListener('dragend', ev => { | |
dragging = null; | |
console.log(ev.type); | |
ev.preventDefault(); | |
}); | |
zone.addEventListener('dragover', ev => { | |
ev.preventDefault(); | |
}) | |
zone.addEventListener('drop', ev => { | |
if (dragging) { | |
console.log(ev.type, ev); | |
const position = JSON.parse(ev.dataTransfer.getData('text/plain')); | |
const clone = dragging.cloneNode(true); | |
const top = calculate(ev.y - position.top); | |
const left = calculate(ev.x - position.left); | |
if (top !== false && left !== false) { | |
clone.style.top = top + 'px'; | |
clone.style.left = left + 'px'; | |
zone.appendChild(clone); | |
ev.preventDefault(); | |
} | |
} | |
}) | |
function calculate(coord) { | |
const point = coord / grid; | |
const multiple = Math.round(point); | |
if (point < multiple + 0.3 && point > multiple - 0.3) { | |
return multiple * grid; | |
} | |
return false; | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment