Been struggling to get this work work. Here's my code:
<canvas id="graphCanvas" ondrop="drop(event)" ondragover="allowDrop(event)" height=600 width=1000 style="border:1px solid #000000;"></canvas>
<img id="img1" src="./images/arrow_up.svg" draggable="true" onmousedown="get_pos(event)" ondragstart="drag(event)"/>
<script type="text/javascript">
function init() {
var canvas = document.getElementById("graphCanvas");
var context = canvas.getContext("2d");
context.lineWidth = 2;
}
var pos;
function allowDrop(ev) {
ev.preventDefault();
}
function get_pos(ev){
pos = [ev.pageX, ev.pageY];
}
function drag(ev) {
ev.dataTransfer.setData("Text",ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var offset = ev.dataTransfer.getData("text/plain").split(',');
var data=ev.dataTransfer.getData("Text");
var img = canvas = document.getElementById("img1");
var dx = pos[0] - img.offsetLeft;
var dy = pos[1] - img.offsetTop;
document.getElementById("graphCanvas").getContext("2d").drawImage(document.getElementById(data), ev.pageX - dx, ev.pageY - dy);
}
</script>
It's suppose to be a draggable image that I can drop into a canvas. Once the image is in the canvas, the user can then move that image around. Unfortunately I can not seem to get it work. The image should appear if you drop it in near the top left, but the image appears near the bottom right.
How can I fix this problem?