我有几个模块:“Shapes.js”是形状对象的容器(模块“Shape.js”)“Mouse.js”将在用户按下鼠标左键时计算坐标,模块“Selection.js”需要进行计算并确定该坐标是否属于形状。
// 鼠标.js
define([], function() {
function Mouse(element, e) {
var offsetX = 0, offsetY = 0;
if (element.offsetParent !== undefined) {
do {
offsetX += element.offsetLeft;
offsetY += element.offsetTop;
} while ((element = element.offsetParent));
}
this.getMouseX = function() {
return e.pageX - offsetX;
}
this.getMouseY = function() {
return e.pageY - offsetY;
}
}
return Mouse;
});
// 选择.js
define(['modules/Shapes', 'modules/Mouse'], function(Shapes, Mouse) {
var selection;
document.getElementById('canvas').addEventListener('mousedown', function(e) {
selection = null;
var mouse = new Mouse(document.getElementById('canvas'), e);
var shapes = Shapes.getShapes();
for(var i=0; i<shapes.length; i++) {
if ((shapes[i].getX() <= mouse.getMouseX())
&& (shapes[i].getX() + shapes[i].getWidth() >= mouse.getMouseX())
&& (shapes[i].getY() <= mouse.getMouseY())
&& (shapes[i].getY() + shapes[i].getHeight() >= mouse.getMouseY())) {
selection = shapes[i];
break;
}
}
});
return selection;
});
为了保持这个问题很小,我不会发布“形状”和“形状”模块,它们并不重要。
所以现在在“main.js”模块中,当用户触发 mousedown 事件但我无法得到它时,我希望始终引用选定元素(或 null)。甚至不知道从哪里开始。如果我只是在主模块中加载选择模块,我总是会得到未定义的。提前致谢。
(代码片段来自 Simon Sarris 画布教程,稍作修改,只是尝试通过 Require.js 完成所有操作)
编辑:@Katana314,你想过这样的事情吗?
// Selection.js(已编辑)
define(['modules/Shapes', 'modules/Mouse'], function(Shapes, Mouse) {
var selection;
return function(e) {
selection = null;
var mouse = new Mouse(document.getElementById('canvas'), e);
var shapes = Shapes.getShapes();
for(var i=0; i<shapes.length; i++) {
if ((shapes[i].getX() <= mouse.getMouseX())
&& (shapes[i].getX() + shapes[i].getWidth() >= mouse.getMouseX())
&& (shapes[i].getY() <= mouse.getMouseY())
&& (shapes[i].getY() + shapes[i].getHeight() >= mouse.getMouseY())) {
selection = shapes[i];
break;
}
}
return selection;
}
});
// Main.js
document.getElementById('canvas').addEventListener('mousedown', function(e) {
console.log(Selection(e)); // Shape... :D
});