The last figure first
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.
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…