Image 在画布上拖动图像
我试图在Image 在画布上拖动图像,image,canvas,drag,Image,Canvas,Drag,我试图在画布元素周围拖动图像。虽然我一直在工作,但它并不像我想的那样工作 基本上,图像总是比画布元素大,但是画布中图像的左侧不能比画布的左侧更右,同样,也不允许右侧比画布的右侧“更右”。基本上,图像被限制为不显示任何空白画布空间 拖动的问题是,每当我开始将图像“pops”拖回,就好像0,0来自鼠标位置,而实际上我想将图像从当前位置移动 document.onmousemove = function(e) { if(mouseIsDown) { var mouseCoord
画布
元素周围拖动图像。虽然我一直在工作,但它并不像我想的那样工作
基本上,图像总是比画布元素大,但是画布中图像的左侧不能比画布的左侧更右,同样,也不允许右侧比画布的右侧“更右”。基本上,图像被限制为不显示任何空白画布空间
拖动的问题是,每当我开始将图像“pops”拖回,就好像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);
}*/
};
这就是我现在拥有的,在这里我得到了一种parallelex效果。你必须记录图像移动时的当前偏移量,并在每次鼠标向下移动时使用该偏移量(除了从画布左上角的偏移量)来确定初始偏移量
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));
};
您可能应该将其视为伪代码,因为我没有以任何方式对其进行测试…;-) 如果我将其复制粘贴到JSFIDLE中,它会重新创建该行为吗?如果没有,请将完整的代码放在jsfiddle.net上,或者至少放在一个最小的示例上?你应该删除它,以免混淆任何人。还有,什么是myNewX/myNewY?