gpt4 book ai didi

javascript - 选择距离鼠标点击最近的对象

转载 作者:行者123 更新时间:2023-12-03 03:06:48 26 4
gpt4 key购买 nike

我想找到距离鼠标点击位置最近的对象。

这可能吗?

我的对象非常小,比如 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;
});

最佳答案

您可以从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);
}
}

完整代码片段

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>

关于javascript - 选择距离鼠标点击最近的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47132201/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com