1

I'm dragging an html element and dropped to a canvas, took the location where released and plot the object at same location at canvas. But showing at the different location. See my code.

Script

function init() { var canvas = document.getElementById("graphCanvas"); var context = canvas.getContext("2d"); context.lineWidth = 2; } function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { ev.dataTransfer.setData("Text",ev.target.id); } function drop(ev) { ev.preventDefault(); var data=ev.dataTransfer.getData("Text"); document.getElementById("graphCanvas").getContext("2d").drawImage(document.getElementById(data), ev.clientX, ev.clientY); } 

HTML

<body onload="init();"> <canvas id="graphCanvas" ondrop="drop(event)" ondragover="allowDrop(event)" height=300 width=300 style="border:1px solid #000000;"></canvas> <img id="img1" src="http://static.tumblr.com/vcbmwcj/foumiteqs/arrow_up_alt1.svg" draggable="true" ondragstart="drag(event)"/> </body> 

1 Answer 1

2

Fixed. Updated code is http://jsfiddle.net/YXxsH/5/. Calculations are done with pageX and pageY and image offset values.

Sign up to request clarification or add additional context in comments.

5 Comments

Sorry, nevermind that variable it's unused. Issue is still not fixed
Already clarified in the question, dropping at one place rendering at another place.
That's nice. But still problem is hidden. Try increase canvas width or height and drop again(Increase up to scroll bar shown).
@ViliusL Is it easy to make the dropped elements moveable inside the canvas? So a user can re-position them after its dropped?
@sjs you have to save or know element position, catch user drag so you know change of x and y coordinates, clear canvas, draw canvas background if you need, redraw wanted element with new position.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.