Canvas Learning notes-trigonometry in animation

Source: Internet
Author: User

Example 1, follow the mouse's key head:

You need to master an important formula that returns the angle from the x-axis to the point
Math.atan2 (DY,DX);

Key code:

1 functionArrow () {2    This. x = 0;3    This. y = 0;4    This. Rotate = 0;5    This. color = ' #ffff00 ';6 }7 8Arrow.prototype.draw =function(context) {9 Context.save ();TenContext.translate ( This. x, This. y); OneContext.rotate ( This. rotate); AContext.fillstyle = This. Color; -Context.linewidth = 2; -  the Context.beginpath (); -Context.moveto (-50,-25); -Context.lineto (0,-25); -Context.lineto (0,-50); +Context.lineto (50, 0); -Context.lineto (0, 50); +Context.lineto (0, 25); AContext.lineto (-50, 25); at Context.closepath (); -  - Context.fill (); - Context.stroke (); - Context.restore (); - }; in  - varCanvas = document.getElementById (' C '), tocontext = Canvas.getcontext (' 2d '), +Mouse =utils.capturemouse (canvas), -Arrow =NewArrow (); the  *arrow.x = CANVAS.WIDTH/2; $ARROW.Y = CANVAS.HEIGHT/2;Panax Notoginseng  -(functionDraw () { the Window.requestanimframe (Draw, canvas); +Context.clearrect (0, 0, Canvas.width, canvas.height); A  the     varDX = mouse.x-arrow.x, +DY = mouse.y-Arrow.y, -Rotate =math.atan2 (dy, dx); $  $Arrow.rotate =rotate; -  - Arrow.draw (context); the})();
View Code

Example 2, Smoothing motion:

Key code

YPos = centery + math.sin (angle) *+ = 0.1;

Example 3, Pulse motion:

Note that you do not need to clear the canvas here, and you should use Beginpath () when you start drawing

Example 4, circular motion:

The main point of the circular motion is to use sine to calculate the x-coordinate, cosines calculates the y-coordinate, the ellipse is the x-axis motion and the y-axis radius is different.

Canvas Learning notes-trigonometry in animation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.