I. Requirements:
Requirements: Let the ball move along the sine wave.
The constructor of the ball is as follows:
The constructor of a sphere
function Ball (radius, color) {
if (radius = = = undefined) {radius = 40;}
if (color = = undefined) {color = ' #ff0000 ';}
this.x = 0;
This.y = 0;
This.radius = radius;
this.rotation = 0;
This.scalex = 1;
This.scaley = 1;
This.color = color;
This.linewidth = 1;
}
Ball.prototype.draw = function (context) {
Context.save ();
Context.translate (this.x, THIS.Y);
Context.rotate (this.rotation);
Context.scale (This.scalex, This.scaley);
Context.linewidth = This.linewidth;
Context.fillstyle = This.color;
Context.beginpath ();
Context.arc (0, 0, This.radius, 0, Math.PI * 2, true);
Context.closepath ();
Context.fill ();
if (This.linewidth > 0) {
Context.stroke ();
}
Context.restore ();
}
Two. Analysis of ideas:
Sine wave function Math.sin (angle) can be used to draw. In which, the angle value as a variable and increment, you can make the object according to the sine wave motion, so as to achieve sine waves animation.
The process is as follows:
(function Drawframe () {
Window.requestanimationframe (Drawframe, canvas);
BALL.Y = Math.sin (angle) * range;
Angle + = speed;
Ball.draw (context);
})();
The following code can be printed in the console to understand the numerical distribution of the lower sine wave:
var Fullradians = Math.PI * 2;
for (var angle = 0; angle < Fullradians; angle + + 0.01) {
Console.log (Math.sin (angle));
}
Three. Examples:
Code:
<canvas id= "Canvas" width= "height=" style= "background": #ccc; ></canvas>
Window.onload = function () {
var canvas = document.getElementById ("Canvas"),
Context = Canvas.getcontext ("2d"),
Ball = new ball (2),
Angle = 0,
Range = 50,
Speed = 0.1,
Isfoward = true;
ball.x = 0;
Ball.y = CANVAS.HEIGHT/2;
ball.linewidth = 0;
(function Drawframe () {
Window.requestanimationframe (Drawframe, canvas);
//context.clearrect (0, 0, canvas.width, canvas.height);
ball.y = canvas.height/2 + math.sin (angle) * 100;
if (isfoward) {
ball.x + = speed * 20;
} else {
ball.x-= speed * 20;
}
if (ball.x > Canvas.width) {
Isfoward = false;
Context.clearrect (0, 0, canvas.width, canvas.height);
else if (ball.x < 0) {
Isfoward = true;
Context.clearrect (0, 0, canvas.width, canvas.height);
}
Angle + = speed;
Ball.draw (context);
})();
};
Four. Summary:
The way to create a sine wave is to use the sine function math.sin (angle) to evaluate, and let the radian value angle according to the movement time increment.
The formula for creating a sine wave is as follows:
/**
* Range: The peak value of the selection
* Intersection point of center:y axis
* Speed: The speed of the sine wave movement
* Angle: Radian value, incremented variable
*/
(function Drawframe () {
Window.requestanimationframe (Drawframe, canvas);
Valeue = center + math.sin (angle) * range;
Angle + = speed;
})();