HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Animating opacity of 1400 Raphael.js objects hurts animating performance

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
objectsanimatingraphael1400opacityhurtsperformance

Problem

I am animating 1400 objects trying to create a 'twinkling effect'. As the user moves the mouse faster more hexagon shapes pop into full opacity and have varying fade out rates. The version in the fiddle fills the space with enough color but feels jerky and clumpy. If I lessen the fade_time variable amounts it is smoother but does not have enough hexagons with full opacity. The end goal is to spell words with the hexagons.

JSFiddle code

Here's the JS if you don't want to go over to jsfiddle:

```
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function shuffle(array) {
var tmp, current, top = array.length;

if(top){
while(--top) {
current = Math.floor(Math.random() * (top + 1));
tmp = array[current];
array[current] = array[top];
array[top] = tmp;
}
}

return array;
}

Raphael.el.animate_hex = function() {
var fade_time = [1000, 2000, 3000, 4000];
//var fade_time = [3000, 4000, 5000, 6000];
this.attr({"fill-opacity": 1});
this.animate({"fill-opacity": 0}, fade_time[getRandomInt(0, 4)], 'linear', function(){
});
};
//set paper to width and height of container
var container_width = document.getElementById('wrap').offsetWidth;
var container_height = document.getElementById('wrap').offsetHeight;
var paper = Raphael(document.getElementById('wrap'), container_width, container_height);

//create and position hexagon shapes.
var set = paper.set();
var abs_x = 0;
var abs_y = 0;
var total_hex = 1400;
for(h=0;h<total_hex;h++){
var HexM = [7.478, 8.66];
var HexL = [[7.478, 8.66], [2.542, 8.66], [0.05, 4.32], [2.542, 0.028], [7.478, 0.028], [9.97, 4.32], [7.478, 8.66]];
var hex = paper.path('M ' + HexM[0] + ' ' + HexM[1] + ' L ' + HexL[0][0] + ' ' + HexL[0][2] + ' L ' + HexL[1][0] + ' ' + HexL[1][3] + ' L ' + HexL[2][0] + ' ' + HexL[2][4] + ' L ' + HexL[3][0] + ' ' + HexL[3][5] + ' L ' + HexL[4][0] + ' ' + HexL[4]

Solution

You are most certainly using a wrong tool for the job. ` element and requestAnimationFrame()` are your friends.

Also, I'd expect opacity animation to tax the graphics stack heavily (unless GPU accelerated, perhaps.) If the background color is going to be white, animating the fill color should work better.

Suggested reading:

-
requestAnimationFrame for smart
animating

-
Cross Browser GPU Acceleration and requestAnimationFrame in
Depth

Context

StackExchange Code Review Q#15259, answer score: 2

Revisions (0)

No revisions yet.