我创建了一个让我移动画布的页面(通过改变X和Y位置)。 这是我的代码:https://jsfiddle.net/rrmwub4h/1/
var canvas = document.getElementById("id1");
var ctx = canvas.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Drag and drop me",10,50);
document.getElementById('id1').onmousedown = function () {
_drag_init(this);
return false;
};
document.onmousemove = _move_elem;
document.onmouseup = _destroy;
var selected = null, // Object of the element to be moved
x_pos = 0, y_pos = 0, // Stores x & y coordinates of the mouse pointer
x_elem = 0, y_elem = 0; // Stores top, left values (edge) of the element
function _drag_init(elem) {
selected = elem;
x_elem = x_pos - selected.offsetLeft;
y_elem = y_pos - selected.offsetTop;
}
function _move_elem(e) {
x_pos = document.all ? window.event.clientX : e.pageX;
y_pos = document.all ? window.event.clientY : e.pageY;
if (selected !== null) {
selected.style.left = (x_pos - x_elem) + 'px';
selected.style.top = (y_pos - y_elem) + 'px';
}
}
// Destroy the object when we are done
function _destroy() {
selected = null;
}
但我想在移动画布时对X和Y位置进行限制(例如0到300px之间,并且不超过300px的限制)
如何将这个条件添加到我的代码中?
答案 0 :(得分:1)
jsFiddle https://jsfiddle.net/CanvasCode/rrmwub4h/2/
var canvas = document.getElementById("id1");
var ctx = canvas.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Drag and drop me",10,50);
document.getElementById('id1').onmousedown = function () {
_drag_init(this);
return false;
};
document.onmousemove = _move_elem;
document.onmouseup = _destroy;
var selected = null, // Object of the element to be moved
x_pos = 0, y_pos = 0, // Stores x & y coordinates of the mouse pointer
x_elem = 0, y_elem = 0; // Stores top, left values (edge) of the element
// Will be called when user starts dragging an element
function _drag_init(elem) {
// Store the object of the element which needs to be moved
selected = elem;
x_elem = x_pos - selected.offsetLeft;
y_elem = y_pos - selected.offsetTop;
//Ext.getCmp("GridMarkeurs").getSelectionModel().select(cmp, true);
}
function _move_elem(e) {
x_pos = document.all ? window.event.clientX : e.pageX;
y_pos = document.all ? window.event.clientY : e.pageY;
if (selected !== null) {
selected.style.left = (x_pos - x_elem) + 'px';
selected.style.top = (y_pos - y_elem) + 'px';
}
if(x_pos >= 300)
{
selected.style.left = "300px";
}
if(y_pos >= 300)
{
selected.style.top = "300px";
}
}
// Destroy the object when we are done
function _destroy() {
selected = null;
}
只需在move_elem
函数中添加if语句,以查看x_pos或y_pos是否超过了值。