N K
N K

Reputation: 3337

Drag and Drop to HTML5 Canvas

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>

Upvotes: 1

Views: 8989

Answers (1)

ViliusL
ViliusL

Reputation: 4745

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

Upvotes: 2

Related Questions