Write a red envelope rain, commemorate those who can still get red envelope years ~

The last figure first

Game core: Master the basic application of Canvas and keep animation smooth.
Core business issues:
1\. Generate red envelopes: red envelopes must be scattered in various places and cannot overlap;

Use timer **setTimeout** or animation function **requestAnimationFrame** to clear and redraw the screen of each frame;

3\. The user clicks on the red envelope and calculates whether the mouse position hits the red envelope.
The concrete implementation idea of the above process can refer to this article: Canvas + Vue to achieve 60 FPS gold grab animation (like Tmall Red envelope rain) (from gold mining user ** Amandakelake **), has described the implementation process in detail, not to repeat here.

Juejin. Cn/post / 684490…

On this basis, two other animations are implemented: swing and zoom.

It is important to understand that the canvas rotation API rotates at the top left (0,0) center point, like this:

So to do the rotation based on the center of the red envelope, use another API: Translate () to transform the coordinates of the canvas.

Rotate should translate back to the point 0,0 otherwise the red envelope will be out of bounds.
Translate (x coordinate on the top left of the red envelope + width of the red envelope /2, Y coordinate on the top left of the red envelope + height of the red envelope /2); ctx.rotate(rotate); Ctx.translate (-top left x-width of the red envelope /2, -top left y-height of the red envelope /2); ctx.translate(-top left X-width of the red envelope /2, -top left y-height of the red envelope /2);Copy the code

Similarly, the scaling effect of red envelopes can be obtained.

Finally, click on the red envelope event monitor is bound to canvas. When clicking on canvas, the coordinate of the mouse is obtained and then compared with the coordinate of the current red envelope.

If (math. abs(top left x - mouse x) < width && abs(top left y - mouse y) < height){//Copy the code

Attention should be paid here, because the animation is very fast, sometimes there is no reaction when you click on the red envelope, you can increase the area of the click appropriately.

Post a Github and help yourself if you need it. If you think it’s ok, click “Star”

Github.com/PeggyWeb/ga…