有一个很棒的教程Selecting Multiple Objects with KineticJS教你如何在 HTML Canvas 中创建一个选择框以选择多个对象,但是作者Michelle Higgins编写了他的代码来选择选择框所包含的对象。
以下 JavaScript 代码表达了该算法:
var pos = rectSel.getAbsolutePosition();
//get the extents of the selection box
var selRecXStart = parseInt(pos.x);
var selRecXEnd = parseInt(pos.x) + parseInt(rectSel.attrs.width);
var selRecYStart = parseInt(pos.y);
var selRecYEnd = parseInt(pos.y) + parseInt(rectSel.attrs.height);
//get the extents of the group to compare to
var grpXStart = parseInt(grp.attrs.x);
var grpXEnd = parseInt(grp.attrs.x) + parseInt(grp.attrs.width);
var grpYStart = parseInt(grp.attrs.y);
var grpYEnd = parseInt(grp.attrs.y) + parseInt(grp.attrs.height);
//Are we inside the selction area?
if ((selRecXStart <= grpXStart && selRecXEnd >= grpXEnd) &&
(selRecYStart <= grpYStart && selRecYEnd >= grpYEnd))
{
if (arSelected.indexOf(grp.getName()) < 0)
{
arSelected.push(grp.getName());
var tmpX = parseInt(grp.attrs.x);
var tmpY = parseInt(grp.attrs.y);
var rectHighlight = new Kinetic.Rect({
x: tmpX,
y: tmpY,
height: grp.attrs.height,
width: grp.attrs.width,
fill: 'transparent',
name: 'highlightBlock',
stroke: '#41d6f3',
strokeWidth: 3
});
layer.add(rectHighlight);
}
}
问题是:如何使选择框不仅选择它所接触的任何对象,还选择它所包含的对象?
PS:这是一个工作jsbin。