gpt4 book ai didi

javascript - Fabricjs 选择鼠标单击多个对象

转载 作者:行者123 更新时间:2023-11-30 11:10:04 25 4
gpt4 key购买 nike

关于在 Canvas 鼠标单击上选择多个对象有什么建议吗?不是所有对象,我想选择覆盖在点上的对象。

据我所知,鼠标事件的目标始终只是最上面的对象。我曾尝试在对象上绑定(bind)事件,但它不会为背面的那些事件触发。我曾尝试根据项目大小和高度进行选择,但旋转后效果不佳。

var canvas = this.__canvas = new fabric.Canvas('c', {
enableRetinaScaling: false
});

function LoopOnObjects(e) {
var mouse = canvas.getPointer(e.e, false);
var x = Math.ceil(mouse.x);
var y = Math.ceil(mouse.y);

var count = 0;
canvas.getObjects().forEach(function(object, index){
if(CheckObjectWithin(object, x, y)) {
count++;
}
});

alert("ya, there is " + count + " objects touch on click");
}

function CheckObjectWithin(object, x, y) {
var objectBoundRect = object.getBoundingRect(true);
var widthRange = objectBoundRect.width;
var heightRange = objectBoundRect.height;

if (x > objectBoundRect.left && x < objectBoundRect.left + widthRange) {
if (y > objectBoundRect.top && y < objectBoundRect.top + heightRange) {
return true;
}
}

return false;
}

function GetElement(e) {
LoopOnObjects(e);
}

canvas.on("mouse:up", GetElement);

canvas.add(new fabric.Rect({
width: 100, height: 100, left: 100, top: 20, angle: -10,
fill: 'rgba(0,200,0,0.5)'
}));
canvas.add(new fabric.Rect({
width: 50, height: 100, left: 220, top: 80, angle: 45,
stroke: '#eee', strokeWidth: 10,
fill: 'rgba(0,0,200,0.5)'
}));
canvas.add(new fabric.Circle({
radius: 50, left: 220, top: 175, fill: '#aac'
}));

template for testing

最佳答案

实际上,已经有一个库方法:fabric.Object.prototype.containsPoint() .它适用于旋转,但请记住,该点是针对边界框而不是可见形状进行检查的(例如,圆形仍然具有矩形边界框)。

var canvas = this.__canvas = new fabric.Canvas('c');

function loopOnObjects(e) {
var mouse = canvas.getPointer(e.e, false);
var point = new fabric.Point(mouse.x, mouse.y)

var count = 0;
canvas.getObjects().forEach(function(object, index){
if (object.containsPoint(point)) {
count++;
}
});
}

function getElement(e) {
loopOnObjects(e);
}

canvas.on("mouse:down", getElement);

canvas.add(new fabric.Rect({
width: 100, height: 100, left: 100, top: 20, angle: -10,
fill: 'rgba(0,200,0,0.5)'
}));
canvas.add(new fabric.Rect({
width: 50, height: 100, left: 220, top: 80, angle: 45,
stroke: '#eee', strokeWidth: 10,
fill: 'rgba(0,0,200,0.5)'
}));
canvas.add(new fabric.Circle({
radius: 50, left: 220, top: 175, fill: '#aac'
}));
#c {
border: 1px black solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.22/fabric.min.js"></script>
<canvas id="c" width="500" height="300"></canvas>

关于javascript - Fabricjs 选择鼠标单击多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54065028/

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