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