canvas animation routines
canvas canvas intention, it should be is the kind of oil painting, so in fact only one painting to draw a picture. But the animation is just a continuous nothing more pictures. If we create a Multi-frame continuous play, it creates animation.
But usually we only create a canvas to the entire animation, therefore, when a picture is painting after time, before a picture is to be erased ctx.clearRect()
. So we need some objects imgObj
to record the location of the current picture of some elements.
So in terms of that whole
- Wipe canvas ctx.clearRect ()
- Calculating the position of the current elements of the painting imgObj
- The element imgObj painting on canvas
- Back to step 1
1 |
let loop = () => { |
RequestAnimationFrame instead of using setTimeout to get better performance.
Creating particles
We need to coordinate to represent the position at which the particles are drawn canvas, while dynamic particles, but also a representation of the speed of its movement.
1 |
let particle = { |
Such a particle motion information may be recorded.
More than a single particle can also add additional information, for example, color, size radius.
Initializing a set of particle information
1 |
the let particleArr = []; |
Draw particle
Cycle call canvas API can be.
Particle update
If you do not do the update before drawing particles that are the same every time we see a picture, the whole movie is static.
In this step, a preserved when creating the position and velocity of the particle before the particle to use it.
We can simply determine the current location of the particles should be in by the speed record.
1 |
let calcParticle = (particle) => { |
This enables the entire screen to move.
But if only this, after a moment, there is no particle on our canvas, because all the particles in the direction of the initialization of non-stop movement "fled" to the outside of the canvas. Thus, when we calculate the longer simply add a collision detection (when the particle radius is small enough, when the moving speed is not) , the particle is determined when the position is outside the canvas reverse speed.
1 |
let calcParticle = (particle) => { |
X and Y axes their duties.
Draw cable
The distance between the particles is determined one by one, and then calculate the transparency of the cable by a maximum distance. Then ctx.lineTo()
the center of the two particles can be.
END
When too many particles back significantly Caton, while the speed is too large will feel when the animation does not seem coherent.