图像未正确放置在画布上

时间:2013-12-11 05:26:32

标签: javascript html5-canvas

http://jsfiddle.net/YXxsH/5/

在jsfiddle之上将图像拖放到画布上 问题是我把代码放在网站上 并放置它在最右侧的图像,而不是放在哪里

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);
}

1 个答案:

答案 0 :(得分:0)

您还需要考虑canvas元素的相对位置。

请参阅:http://jsfiddle.net/FgM48/

var img = document.getElementById("img1");
var canvas = document.getElementById("graphCanvas");
var dx = pos[0] - (img.offsetLeft - canvas.offsetLeft);
var dy = pos[1] - (img.offsetTop - canvas.offsetTop);