我想找到鼠标点击位置最近的对象。
这可能吗?
我的物品非常小,就像DOT一样。所以我无法选择它们,我想可能是我可以找到鼠标点击位置最近的对象。
有没有办法找到它?
var canvas = new fabric.Canvas('c', { selection: false });
var circle, isDown, origX, origY;
canvas.on('mouse:down', function(o){
isDown = true;
var pointer = canvas.getPointer(o.e);
origX = pointer.x;
origY = pointer.y;
circle = new fabric.Circle({
left: pointer.x,
top: pointer.y,
radius: 10,
fill: 'red',
selectable: false,
originX: 'center', originY: 'center',
});
canvas.add(circle);
canvas.renderAll();
});
canvas.on('mouse:up', function(o){
isDown = false;
});
答案 0 :(得分:1)
您可以从canvas._object
获取最近的对象。
这里是mouse:move
事件。
for ( i = 0; i < canvas._objects.length; i++){
if(Math.pow(canvas._objects[i].left - origX,2) + Math.pow(canvas._objects[i].top - origY,2) < minLength){
minObj = canvas._objects[i];
minLength = Math.pow(canvas._objects[i].left - origX,2) + Math.pow(canvas._objects[i].top - origY,2);
}
}
FULL CODE代码段
var canvas = new fabric.Canvas('canvas', { selection: false });
var circle, isDown, origX, origY;
canvas.on('mouse:down', function(o){
isDown = true;
var pointer = canvas.getPointer(o.e);
origX = pointer.x;
origY = pointer.y;
circle = new fabric.Circle({
left: pointer.x,
top: pointer.y,
radius: 10,
fill: 'red',
selectable: false,
originX: 'center', originY: 'center',
});
canvas.add(circle);
canvas.renderAll();
});
canvas.on('mouse:move', function(o){
var minLength = 10000000;
var minObj = null;
var pointer = canvas.getPointer(o.e);
origX = pointer.x;
origY = pointer.y;
for ( i = 0; i < canvas._objects.length; i++){
if(Math.pow(canvas._objects[i].left - origX,2) + Math.pow(canvas._objects[i].top - origY,2) < minLength){
minObj = canvas._objects[i];
minLength = Math.pow(canvas._objects[i].left - origX,2) + Math.pow(canvas._objects[i].top - origY,2);
}
}
for ( i = 0; i < canvas._objects.length; i++){
if(canvas._objects[i] == minObj){
canvas._objects[i].set({fill: 'blue'});
}else{
canvas._objects[i].set({fill: 'red'});
}
}
canvas.renderAll();
});
canvas.on('mouse:up', function(o){
isDown = false;
});
canvas.add(new fabric.Circle({
left: 10,
top: 10,
radius: 10,
fill: 'red',
selectable: false,
originX: 'center', originY: 'center',
}));
canvas.add(new fabric.Circle({
left: 100,
top: 100,
radius: 10,
fill: 'red',
selectable: false,
originX: 'center', originY: 'center',
}));
canvas.renderAll();
<canvas id="canvas" width="800" height="600"></canvas>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js"></script>