在画布上拖动图像
问题描述:
我正在尝试将图像拖入canvas
元素。虽然我拖着工作,但它不工作,因为我很喜欢。在画布上拖动图像
基本上,图像总是大于画布元素,但画布内图像的左侧不能比画布左侧更右侧,同样右侧不允许“比画布的右侧更“正确”。基本上,图像被限制为不显示任何空白画布空间。
拖动的问题是,无论何时我开始将图像“弹出”拖回来,就好像0,0来自鼠标位置,而我实际上想从当前位置移动图像。
document.onmousemove = function(e) {
if(mouseIsDown) {
var mouseCoords = getMouseCoords(e);
offset_x += ((mouseCoords.x - canvas.offsetLeft) - myNewX);
offset_y += ((mouseCoords.y - canvas.offsetTop) - myNewY);
draw(offset_x, offset_y);
// offset_x = ((mouseCoords.x - canvas.offsetLeft) - myNewX);
// offset_y = ((mouseCoords.y - canvas.offsetTop) - myNewY);
// offset_x = (mouseCoords.x - canvas.offsetLeft) - myNewX;
// offset_y = (mouseCoords.y - canvas.offsetTop) - myNewY;
offset_x = prevX;
offset_y = prevY;
}
/*if(mouseIsDown) {
var mouseCoords = getMouseCoords(e);
var tX = (mouseCoords.x - canvas.offsetLeft);
var tY = (mouseCoords.y - canvas.offsetTop);
var deltaX = tX - prevX;
var deltaY = tY - prevY;
x += deltaX;
y += deltaY;
prevX = x;
prevY = y;
draw(x, y);
}*/
};
是我现在所拥有的,在那里我得到了平行效应。
答
您必须在图像移动时记录图像的当前偏移量,并将每个mousedown的图像(除了画布左上角的偏移量)用于确定初始偏移量。
var dragging = false,
imageOffset = {
x: 0,
y: 0
},
mousePosition;
function dragImage(coords) {
imageOffset.x += mousePosition.x - coords.x;
imageOffset.y += mousePosition.y - coords.y;
// constrain coordinates to keep the image visible in the canvas
imageOffset.x = Math.min(0, Math.max(imageOffset.x, canvas.width - imageWidth));
imageOffset.y = Math.min(0, Math.max(imageOffset.y, canvas.height - imageHeight));
mousePosition = coords;
}
function drawImage() {
// draw at the position recorded in imageOffset
// don't forget to clear the canvas before drawing
}
function getMouseCoords(e) {
// return the position of the mouse relative to the top left of the canvas
}
canvas.onmousedown = function(e) {
dragging = true;
mousePosition = getMouseCoords(e);
};
document.onmouseup = function() {
dragging = false;
};
document.onmousemove = function(e) {
if(dragging) dragImage(getMouseCoords(e));
};
你或许应该将此视为伪因为我没有以任何方式测试了它... ;-)
如果我复制粘贴到的jsfiddle将它重新的行为?如果没有,请将完整的代码放在jsfiddle.net上,或者至少是一个简单的例子。 – puk 2012-01-05 00:05:15
为什么你有被注释掉的代码?你应该删除它,不要混淆任何人。另外,什么是myNewX/myNewY? – puk 2012-01-05 00:08:51