Therefore, so far
As usual, article life on Habré does not last more than 1.5 days therefore it is impossible to calculate an event of effective. But after New Year there are different miracles: the flow of visitors falls, and accidental sleepwalkers get chance not to forget one article of the whole 5 days. On them it is also staked.
Better if it is attached to long process, for example, to club of Anonymous Fathers Frost, coming into which it will be always possible to receive a binding to discussion and development of options of "snow falling" and at the same time it is not attached strictly to a holiday. Result now — here: geekadm.ru/#/2015, also is, of course, intermediate experiments like 188.8.131.52/snow.html? v=4 — snow for HabraAdm with additional effects.
Preliminary "hackathon" was organized by couple of participants and (or) visitors of club — (1), (2). As a result, about 10 options on the engine with Canvas turned out. Their number can be much more, but on everything free time therefore the event turned into open is necessary. For example, it is possible "to fasten" the model of falling of snowflakes by the author of Peter Gehrig which is already written in 2003 to the engine. Completion in 2005-2006 shows on modern browsers that 20-30 snowflakes are slightly loaded by the processor (10-20%, depend on the power and the video card; let's speak hereinafter about loading of one kernel of the processor since JS — one-line), and according to old forums, similar was also on old Opera 9 and IE6 browsers, but it is slightly worse. On Canvas with the same algorithm it would be possible to start time in 5 more objects.
Let's glance in history and we will look at its course
Let's begin with the beginning, since 2002-2005 approximately. Dzhavaskript showed capability to animate falling of snowflakes. However, it appeared, and it was natural, animation on a script or unproductive, or strongly loads the processor. Therefore and in those old times it was necessary or to save very much resources, or to load the processor to the maximum, for 100% in a browser flow, (on 1 kernel) that braked other tabs (in those Opera 9 browsers where they were) and windows, and it aroused badly hidden indignation of visitors of such pages.
In years 8 the solution of this problem at the level of the browser was found. The main browsers, since Chrome, began to stop execution of scripts on invisible tabs. It helped not to prevent viewing of other windows and programs (but does not stop upon transition to other window but only loading decreases if the window is not drawn on the screen or it is visible partially). However, in connection with a mobile era, opening of pages with the loading animation, all the same, is not perceived positively.
Canvas as it will be visible in examples, allows to start one hundred snowflakes with loading 30-40% for the average desktop computer or the notebook. It is about 5 times more effective, than the best optimized algorithms on JS+DOM are able.
As a history tribute, we will consider also "classical" algorithms which are waiting in the wings for optimization and transfer into Canvas.
It is easy to find many algorithms search in Github according to the type "snowfall js", "snow flakes js". They will add the good selection from 12 scripts with a demo links mentioned above (or the expanded copy).
The overview of algorithms with examples
(When viewing pages with examples be ready to sometimes 100% loading of a kernel of the processor. At demonstration of the link in article about the level of loading it is warned.)
Many algorithms except that are inefficient, also are not similar on behavior to real behavior of snowflakes. Probably, much remembers the evident mismatch of reality the movement of snowflakes on a sinusoid. Once what was seen (or is newer), it is remembered for a long time as a negative example. Therefore, a problem of algorithm — to be not only effective, but also reflecting reality. (By efficiency, calculation of harmonic functions has to lose too.)
From earlier reviewed algorithms as the closest to reality it is possible to consider two — with accidental movements (it is necessary to vary speeds, but not coordinates) and the mentioned algorithm of Peter Gehrig (2003) in which the movement is controlled 4 variables, and one of them which — is harmoniously changing that creates periodic effects of "turbulences". However, about it it is possible to argue and add new implementations to a moneybox.
Let's tabulate what was seen where we will show:
*) quantity of particles;
*) animation type;
*) existence of a sandbox for experiments;
*) loading of the processor (MacBook, Firefox 43) (Chrome usually % 10 more effective);
*) comments on features.
(Real these loadings of the processor will differ from specified for different computers, for computers with different video cards and for mobile devices over a wide range. Are given for orientation for the srednemoshchny notebook with the built-in graphics.)
Let's look quicker at scripts using Canvas.
|Not pure JS||Demo: 400x400, Snowman with Falling Snow|
|Particles on a demo: 100|
|Sandbox — DA|
|Code lines: 106 +ProcessingJS (800K)|
|It is drawn in the environment of ProcessingJS on 800K of an uncompressed code, creating "Rapier" language. The snowman is drawn by the same code. An example — special. Shows that with covers it is possible to heap up anything (for a solution of simple tasks by difficult methods), and even in this case Canvas not catastrophically loses to solutions on DOM.|
|Article (en), 2012||Code: Github||Demo: all screen|
|Particles on a demo: 500|
|Code lines: 50 + 100 in *.html +ThreeCanvasJS (72K)|
|72 To a compressed unpacked code of ThreeCanvas.js library. 3D - a scene with rotation by its movement of a mouse. Here for the sake of the smooth movement small bitrate therefore everything is beautiful, but as background action — not too suitably is put.|
|Year: 2010||Code: JS||Demo and description: all screen|
|Particles on a demo: 60, turn in the drawing plane|
|Code lines: 160|
|Very frequent animation does not allow and to evaluate Canvas advantages here. There is a rotation of the drawn snowflakes round its pivot-center, slow falling with wanderings. But the part of them "goes" on sinusoids, torsion in one plane does not give realness at all that, on the contrary, tears away from perception of effect, creates more likely effect of importunity. The code — on the contrary, shows the power and compactness. In the sum — excellent efforts are directed to achievement a few not those effects that for the consumer — it is not better than the engines eating energy on DOM.|
Let's look at examples of the scripts working with DOM (layers) without Canvas.
|Year: 2009||Demo: jSnow – jQuery Snow Effect, all screen||Code: JS (uncompressed former version)|
|Particles on a demo: 25|
|Code lines: 160 + jQuery|
|Options in Fiddle sandboxes (character snowflakes are used everywhere):
|At this script — characteristic handwriting of particle motions (it is strong in the parties). If to look narrowly is the just very big sinusoids which are perceived as one big whirlwind in the middle of a window. It is very reserved on expenditure of resources. The source code of version 1.2 — is lost or always was obfustsirovan a packer; the unpacked versions 1.1.mod2 (finished by other authors) — are in Codepen sandbox, but do not work with new jQuery because address the cancelled $ .browser. And in them unpacking traces are visible. Perfectly looks in low headings (example) when sinusoids do not manage to be missed. From tens of examples if it is worth getting accustomed to couple from them (on execution and a code), then this example — one of them. Therefore we will undertake the jSnow version thoroughly, having started in a sandbox.
Further it became more interesting — in a code at the tested settings a number of bugs was found (and it does not mean that there were all). Some changes in a code should be done (to clean incompatibility with jQ 2+, calculation of initial provision of a snowflake, not to allow to come it for the left edge of a window — in poppies it leads to "flash" of scroll bar, and it is useful to do the same for the lower bound) therefore it is better to use the modified modern versions.
Versions modes (2009-2010) added couple of essential "features" — settings of a smooth ischezaniye of snowflakes in the bottom of (fadeAway: 1) and a possibility of scrolling with not movement of a field of snowflakes (followScroll: 1). Names are left original what were called by their developers.
The purpose of debugging of an old code is in that then to transfer algorithm to Canvas and to compare speeds.
So, the readable code turned out, is 20 lines shorter (90 lines) and in packed form is 30% less (1.5K), than the best samples of spendthrifts, without having lost at the same time functions and having added stop start button. This intermediate option is compact, but works, as before, with a window and can absolutely set height (height: number) in parameters. It is not really convenient especially as the plug-in does not use a context collection in general therefore it normally feels with a challenge of a strange type of $ () to .jSnow (...), i.e. without context. It turned out quite simply, we will be limited to the link to a demo here.
Also we will complicate a task — to begin to work with the context jQuery collections. Let's save this behavior, when there is no a context — we select work with a window, as well as at a context of window and $ ('body')) and we will add work with the block container (for example, to start for $ (to '.contSnow') .jSnow (...)). The container should be prepared, for it position:relative that the inserted block with absolute well felt is necessary. The block which on all window, will begin to behave in a different way too will cover a window therefore all content of the page will be required to be lifted if there is such block. (It is possible and differently, as before, but why to complicate? Will use more likely, either the first script, or the second.) It will turn out approximately so:
A little the fact that pictures — large and transparent influences.
Really, why to work only with one container if jQuery can provide a collection? Something turns out like it, loading of 30-50% for the sum in 70-120 particles. The stop start can be separated by buttons too or to make the general.
In attempts to apply written at once impracticality of start of a script on a collection is evident. To start — yes, it is possible, even tens of instans of scripts, distributing to everyone on slightly snowflakes. But identical parameters are reported to all blocks of a collection, and it — is impractical since there is a frequent wish to make other task — to start a few windows (virtual, on miracles), but with different parameters, and for this purpose it is necessary to report them to one element. It turns out, most often, that how many elements, starts of .jSnow are necessary so much that turns out long, though is evident.
There is an analogy to writing of the rules CSS. Rules are the same declarations of parameters what we do at starts of plug-ins, even selectors at plug-ins stand on the place. But is not present to mekhaniza gradually now to accumulate descriptions of rules (just as in one — font-size, in the friend — position). The second start of a plug-in on the same element adds one more instans a plug-in (long-playing function with short circuit and a possibility of switching off), but does not add properties to already started. At the same time it would be more convenient to list selectors (just lines with classes), but not JSON-y of settings. But any plug-in where such method of designing of settings would be necessary will not be remembered and worked. On the most advanced option of a demo we will write start in 4 areas as the plug-in is able now:
demo, (a cat in a repo)
Completions of a plug-in added about 300 bytes of a compressed code, but now it with the bigger basis can be called a plug-in. However, without uniform method.
Other scripts for work with DOM
Such attention is paid to one script which is not most advanced because if to glance forward, it is the small competitor to scripts on Canvas, not the fact that above, and it is good economically written. Inefficiently written will not become competitors therefore in a code it is impossible to allow anything superfluous that was that to what to compare.
For example, there is very popular script on DOM under the name Snowstorm, with a compressed code 20K, very large number of settings, shutdown in mobile devices — is to what to learn also for small scripts. But to study that there superfluous and whether leads it to losses — too complex challenge. It is simpler to write small and to expand settings. The importance of everyone will become clear on tests and practice.
Let's quickly walk on one more small script which is not found among well issued demos and sandboxes, but has interesting behavior (it was mentioned above, the author of P.Gehrig). There are no big difficulties does not demand to place it in a sandbox — completions of bugs, jQuery does not use, but it was required to accustom to a modern doktayp. Also, it was bad with special characters of Unicode at system fonts earlier, now — it is better therefore the falling letters are replaced with the falling tekstovay (azured) snowflakes.
|Year: 2005, falling-snow with settings, a code, jsFiddle|
|Particles on a demo: 25|
|Loading: 10% (because of 8 FPS)|
|Code lines: 90|
|So small loading of system is caused in original settings of a script by the low exposed FPS. It, of course, is noticeable by the movements as a frequent slideshow. It was necessary for old browsers and is warned in old comments to a script. At 30 FPS — loading of 35%, approximately as much as will be at the previous script at the same settings.
This script has a modification with adding of Brownian motion and with falling as if "from far away" of the screen, increase and "thawing" (increase in transparency) close or below.
|Year: 2006, falling-snow with falling "published" with settings, jsFiddle|
|Particles on a demo: 25||
(to look in the full screen)
|Loading in jsFiddle: 60% (16 FPS)|
|Code lines: 100|
|Here settings of the sizes "are rather whimsical" — little change of growth rate it is possible to receive huge snowflakes or not growing therefore other scenarios of behavior need to be selected, and showiness will depend finally on the sizes of a window and behavior (does not avtonastraivatsya). Noticeable increase of loading is connected with otrisovny big transparent characters (images). (The source code is written densely, the real quantity of a code after thinning would be twice more.)
Let's write all options of a code with the snow on Gitkhab. Let's consider defects of predecessors who did not write a demo pages and therefore looked at their code much less people. Gitkhab extremely just allows to start a demo if to work in gh-pages branch. Now all modifications of versions are easily fixed in the history of changes and distinctions look. Gitkhab: github.com/spmbt/snowfalls.
How there with CSS animations?
We watch the examples written by others, further in search of effective algorithms and effective results.
1. An example (only with animations of CSS) strongly loading animation on CSS3 with rotation of DOM snowflakes — www.jqueryscript.net/animation/jQuery-Plugin-For-Snowfall-Effect-with-Rotating-Snowflakes.html. (On this website there is everything — the description, a code and a demo for each script, but without sandboxes.)
2. Animation on 3 kartinochny layers in CSS (Codepen).
We try to watch still animations on a kanvasa to find the script which is not strongly loading system.
Example of animation on Canvas which is activating software the movement of a mouse where it is possible to see that acceptable quantity of snowflakes — not continuous generation with about 200-300, and about 50-100 on the screen — www.jqueryscript.net/animation/Yet-Another-Falling-Snow-Animation-with-jQuery-Canvas-GlauserChristmas.html.
One more animation on Canvas without libraries, with a demo and comments on Chinese: www.jqueryscript.net/animation/Nice-Snow-Falling-Effect-with-jQuery-Canvas-Nice-Snowing.html.
All these animations, including Canvas, are for some reason configured so that load the processor for 100% (more precisely, one kernel which can load one-line JS). It as if is considered normal for demonstrations of scripts. (Perhaps, on discrete video cards it indeed.)
Somehow all this is strange
With the snow occurs among scripts very little saving processor loading though they are both for DOM, and for Canvas. Let's show that the same effect of a full load can achieve not for 100, and for couple of thousands of snowflakes, and as normal it is better to consider loading of a kernel for 10-20% for 200-400 pieces.
We select effective Canvas
However, there was one economic script on pure Canvas. We will do the examples approximately in its style.
|Particles on a demo: 25|
|Sandbox — DA|
|Code lines: 90|
|The example shows that if we control all code which does not do anything superfluous as it occurs in examples above, then the success is close. Loading even with 200 particles (in Chrome) makes 45% (it is necessary to watch 2 or 3 processes — Chrome and two Chrome helper) and 60% at 2000. For Firefox — approximately the same, unless for 10% more slowly (under good conditions) and more than the arbitrary braking factors.|
In more detail, results such. We take jsFiddle as less influencing results, we copy an example with adding of a stop button there. We start different quantity of snowflakes, we wait for about a minute while expenses of the processor calm down (without moving a mouse, without doing anything). We watch results through Activity Monitor (MacBook with video Intel HD Graphics 5000). If to look at Windows, say, on the 4-core processor, then we will see loading no more than 25%. 100% called here in article treat loading of one kernel, i.e. 25% should be multiplied on 4. Just browsers so far in a different way are not able to be parallelized, but also this loading is rather sensitive for the notebook, results in power consumption, approximately as when viewing video.
Not started drawing of-10% of loading (background).
0 particles — 30%;
2 chastia — 35%;
25 particles — 40%;
200 particles — 50%;
1000 — 55%;
2000 — 65%.
At the same time not always indications repeat, depends on other started programs and employment of memory.
Here and a solution of why with the advent of Canvas all did not start programming on it at once. Processors, initial possible imperfection of implementation and incomplete support in browsers did not allow to do acceptable bitrate that with high quality of the movement to pass the "qualification of performance" depending not on number of particles, and on bitrate and to keep within at the same time ideally 20%. With animation on layers it is possible to start at least 5 particles and to pass this qualification. Now with a performance it became better, and IE8 which without Canvas, occupies a share about 0.5 percent.
The algorithms on a kanvasa
Let's create the options of economic algorithms on a kanvasa. At first we will close the plane in the torus and we will start up snowflakes downwind with small random walks which are applied to the speed of each particle. It turns out quite naturally though without impression about flaws. The second effect — parallax when more fine particles fall more slowly that creates feeling of tridimentionality of a scene.
With such installations the first pancake went.
|Year: 2015||Demo and sandbox: wind with falling and random walks of speed, all screen wrapped in the torus|
|Particles on a demo: 100|
|Sandbox — YES|
|Code lines: 50|
|Randomness of wanderings leads to the fact that some particles, their quite large number, fly, gradually changing the direction and fly more and more randomly. "Attenuation" of deviations of speed that the swarm of particles was given to the general flow is necessary. The multiplier *.999 in a code creates this "quieting". But affects speed in general therefore over time they will be slowed down more and more. It is not suitable for infinite falling, but falling within the screen is necessary.
The following step is a creation of the earth. Snow on it will stop and thaw that, having thawed, particles appeared on top again (for simplicity there will be meanwhile an identical number of particles, without optimization).
|Demo 2 and sandbox: A scene with thawing of snow in the bottom of a window, all screen|
|Particles on a demo: 1000|
|Sandbox — YES|
|Loading: 40-50% (30 FPS)|
|Code lines: 50|
|The value of particles influences where they will stop: the more a particle, the closer to a window bottom. It creates effect of tridimentionality and accidental filling of "earth" with snowflakes too.
In the beginning it is necessary to start a snow charge more powerfully that the cover was quickly formed. In a minute it in the eyes will begin to thaw, and completely thawed chastitsv from below pass upward. Water cycle.
For initially equilibrium process, of course, it is necessary to deliver evenly snow from heaven. But also seasons of thawing and snow charges have the charm and a neskuchnost. From this demo immediately we receive the picture with deer, the link to which was at the top of article (a code in a sandbox, 30% of loading, 120 particles).
Kafeman scripts within a hackathon
In parallel scripts with snow and other festive effects were done by kafeman.
Initial idea — to construct the welcome page with effects for visitors of ADM club. Everything could be more serious, but history does not suffer a subjunctive mood. Except purely decorative design, the idea to look at real snowfall (1, 2, 3) and to simulate those unpleasant close flickering snow particles visited. Perfection is not reached yet, but the direction has all reasons, otherwise the distracting snow which is molded on the person will not be remembered. Here it is necessary to experiment with drawing of shapeless flakes and their greased flashing.
Also it is necessary to let grow somehow snow cover: jsfiddle.net/162e4jte/3, but not so that it absorbed all planet with the astronaut on it. First he laid down hillocks too and thawed: jsfiddle.net/162e4jte/1. Such behavior met in scripts of other authors.
Nakoyets, on the future idea of consolidation of generators of engines in one deserves execution too. By results, except the mass of scripts of third-party authors, we have 3-4 algorithms of particle motion and 2 methods of implementation which common parts rather well on the provided sandboxes and a repo are traced.
2 programming method snow, really feasible for effect — DOM layers and Canvas — have the niches of application. To about 50 particles wins DOM, but not in all modes, for tasks where small load of the processor is necessary. High bitrate lowers a level. More than 50 (but it is sure — more than 200) — but too with are desirable low bitrate — wins Canvas. But it is necessary to fork up on loading more — from 30% of resources of the processor. The border and criteria — is very unsteady and depends on the equipment, the browser, progress of implementations of the engine in browsers. The mobile user will tell categorical "no" to more than 5 particles, and the statsionarnik with the big video card sincerely will not understand in what problems with 200 particles in DOM and with 5000 in Canvas.
All superfluous of algorithm for typical commercial application (attention of the user around holidays) it is necessary to clean, test algorithms on different devices and to make decisions on a niche of a covering of users. Can be more advantageous nizkobitreytny illumination on Canvas or short-term fireworks on it. Will not prevent to prompt what button to switch off animation and to remember in settings of the user that "the event fulfilled". As not so monetary snow as Yandex browser, is not present the bases "to break" this button consciously. Still in a couple of years it is possible to hope that provision with kanvasy will improve, and it will slowly select to itself(himself) the area of small quantity of particles and the increased bitrate.
Expressive opportunities of scripts of snow, generally at this stage are settled (nothing qualitatively new appeared in this group in recent years). At enough complete scripts there is a number of the properties recognized necessary, and the part of properties, impracticable on productivity (rotation of snowflakes in the 3D format) is not executed, but it confuses nobody. But because of productive drawing on a kanvasa it is possible to expect that such scripts will appear (with loading from 30%).
Coding perspectives — can be written designers who would give object for DOM or Canvas for settings. Designers could write different authors. With such approach the project on Habraadm is organized (Gitkhab): github.com/clubadm/snowmachine.
The users only registered can participate in poll. Enter, please.
This article is a translation of the original post at habrahabr.ru/post/274535/
If you have any questions regarding the material covered in the article above, please, contact the original author of the post.
If you have any complaints about this article or you want this article to be deleted, please, drop an email here: firstname.lastname@example.org.
We believe that the knowledge, which is available at the most popular Russian IT blog habrahabr.ru, should be accessed by everyone, even though it is poorly translated.
Shared knowledge makes the world better.