performance optimization of snap points using drag and drop in RaphealJS
I have a demo page where I am looking at the performance of around 300 points that an object should snap to when being dragged.
http://jsfiddle.net/digiguru/rVFje/
I have optimized it by loading the bounds of each "snap" point into 4 arrays when the drag is started.
var circleT = [];
var circleR = [];
var circleB = [];
var circleL = [];
var start = function (event) {
this.ox = this.attr("cx");
this.oy = this.attr("cy");
var threshold = 15;
for (var myCircle in circles) {
circleT[myCircle] = circles[myCircle].attr("cy") - threshold;
circleR[myCircle] = circles[myCircle].attr("cx") + threshold;
circleB[myCircle] = circles[myCircle].attr("cy") + threshold;
cir开发者_JAVA技巧cleL[myCircle] = circles[myCircle].attr("cx") - threshold;
}
circle.animate({ r: 20,fill: "#319F40", "stroke-width": 1 }, 200);
},
Then in the move event we use the following to calculate the dragged object from each of the snap points...
move = function (mx, my) {
var inrange = false;
var mouseCX = this.ox + mx;
var mouseCY = this.oy + my;
var lockX = 0;
var lockY = 0;
for (var myCircle in circles) {
if ((circleT[myCircle] < mouseCY
&& circleB[myCircle] > mouseCY )
&& (circleR[myCircle] > mouseCX
&& circleL[myCircle] < mouseCX )) {
inrange = true;
lockX = circles[myCircle].attr("cx");
lockY = circles[myCircle].attr("cy");
}
}
if (inrange) {
this.attr({
cx: lockX ,
cy: lockY
});
} else {
this.attr({
cx: mouseCX ,
cy: mouseCY
});
}
},
Genrally performance, is good, but you can notice frames dropping on slightly older IE browsers (IE8 and below). Is there a ninja way to improve performance at all? Perhaps I can improve the 4 if statements? Would using another javascript library like processing JS yeild better results?
Currently you consider every circle on every iteration. You could improve performance by considering fewer circles using a technique similar to this.
http://en.wikipedia.org/wiki/Quadtree
Basically, create bounding boxes for collections of circles. If the circle you are dragging is out of bounds then don't consider any circle within the bounding box. I hope this helps.
精彩评论