I'm recently working on a project that involves animation in the background. It works well on desktop but performance drops drastically on mobile. I'm using Paper.js to import a svg and animate it. This is the demo.
paper.project.importSVG(svg, function(item) {
var moveSpeed = 70;
var movementRadius = 15;
var boundingRec = item.bounds;
var lines = [];
var circles = [];
/*
Arrange lines and circles into different array
*/
$.each(item.getItems({
recursive: true,
}), function(index, item) {
if (item instanceof paper.Shape && item.type == 'circle') {
item.data.connectedSegments = [];
item.data.originalPosition = item.position;
circles.push(item);
}
if (item instanceof paper.Path) {
lines.push(item);
}
});
/*
Loop through all paths
Checks if any segment points is within circles
Anchors the point to the circle if within
*/
$.each(lines, function(pathIndex, path) {
$.each(path.segments, function(segmentIndex, segment) {
$.each(circles, function(circleIndex, circle) {
if (circle.contains(segment.point)) {
circle.data.connectedSegments.push( segment.point );
return false;
}
});
});
});
/*
Animate the circles
*/
$.each(circles, function(circleIndex, circle) {
var originalPosition = circle.data.originalPosition;
var radius = circle.radius * movementRadius;
var destination = originalPosition.add( paper.Point.random().multiply(radius) );
circle.onFrame = function() {
while (!destination.isInside(boundingRec)) {
destination = originalPosition.add( paper.Point.random().multiply(radius) );
}
var vector = destination.subtract(circle.position);
circle.position = circle.position.add(vector.divide(moveSpeed));
// move connected segments based on circle
for (var i = 0; i < circle.data.connectedSegments.length; i++) {
circle.data.connectedSegments[i].set({
x: circle.position.x,
y: circle.position.y,
});
}
if (vector.length < 5) {
destination = originalPosition.add( paper.Point.random().multiply(radius) );
}
}
});
});
A single SVG animation alone is causing the CPU usage to go up to 90% on mid-tier mobile devices and it go to the point that the interface becomes unusable. Any advice or help is much appreciated.