简体   繁体   English

拖放到HTML5画布

[英]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. 我将html元素拖放到画布上,移至释放的位置,并在画布上的相同位置绘制对象。 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 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>

Fixed. 固定。 Updated code is http://jsfiddle.net/YXxsH/5/ . 更新的代码为http://jsfiddle.net/YXxsH/5/ Calculations are done with pageX and pageY and image offset values. 使用pageXpageY以及图像offset值进行计算。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM