Add a dynamic background to a Web page with canvas

Source: Internet
Author: User
Tags cos sin

Recently just received for the public account "play to Sanlitun" production of the first page of the task. Considering that the page is only viewed on the phone, and the phone's support for canvas is very good, you're going to use canvas to do something different.

First of all, look.


To achieve such an animation the ordinary CSS3 is beyond, only use canvas. Fortunately, using canvas is also very simple.

Step1.

Create a new canvas (<canvas>) element and place it underneath all the buttons and logos to avoid obscuring the front elements.

<canvas id= "Canvas" style= "POSITION:ABSOLUTE;TOP:0PX;LEFT:0PX;Z-INDEX:1;" ></canvas>  


Set the canvas's width height to the width of its parent element to fill his parent element. can also be used directlywindow.innerheight,window.innerwidth. Make it fill the entire screen.

var canvas = document.getElementById (' canvas '); var ctx = Canvas.getcontext (' 2d '); canvas.width = Canvas.parentnode.offsetwidth;canvas.height = Canvas.parentNode.offsetHeight;


var canvas = document.getElementById (' canvas '); var ctx = Canvas.getcontext (' 2d '); canvas.width = Canvas.parentnode.offsetwidth;canvas.height = Canvas.parentNode.offsetHeight;
Step2.

Draw a rectangle that fills half the screen in the canvas.

We just need to find the coordinates of the four-point rectangle, use the canvas's drawing path, and populate the path. The four points were:

(0, Canvas height t/2)
(Canvas width, canvas height t/2)
(Canvas width canvas height t/2)
(0, Canvas height t/2)

Note: the coordinates (0,0) are in the upper-left corner of the canvas.

Fill Color Ctx.fillstyle = "Rgba (0,222,255, 0.2)";//Start Drawing path Ctx.beginpath ();//upper left corner ctx.moveto (0, CANVAS.HEIGHT/2);// upper right corner Ctx.lineto (Canvas.width, CANVAS.HEIGHT/2);//Lower right corner Ctx.lineto (Canvas.width, canvas.height);//lower left corner ctx.lineto (0, Canvas.height);//upper left corner ctx.lineto (0, CANVAS.HEIGHT/2);//closed Path Ctx.closepath ();//fill path Ctx.fill ();


Fill Color Ctx.fillstyle = "Rgba (0,222,255, 0.2)";//Start Drawing path Ctx.beginpath ();//upper left corner ctx.moveto (0, CANVAS.HEIGHT/2);// upper right corner Ctx.lineto (Canvas.width, CANVAS.HEIGHT/2);//Lower right corner Ctx.lineto (Canvas.width, canvas.height);//lower left corner ctx.lineto (0, Canvas.height);//upper left corner ctx.lineto (0, CANVAS.HEIGHT/2);//closed Path Ctx.closepath ();//fill path Ctx.fill ();

To run the code:


Step3.

Let the rectangle move up. To animate we need to continuously empty the canvas and redraw the new rectangle, just as the movie plays 24 pictures per second. We create a loop function to draw an image of each frame and use Requestanimframe to tell the browser to use loop to draw each frame.

Use Requestanimframe if the browser supports requestanimframe otherwise use Settimeoutwindow.requestanimframe = (function () {return  Window.requestanimationframe       | | Window.webkitrequestanimationframe | | Window.mozrequestanimationframe    | | Function (callback) {          window.settimeout (callback, 1000/60);        };}) (); function loop () {requestanimframe (loop);} Loop ();


Put the previously drawn rectangle code in the loop and clear all the graphics in the canvas before you draw the rectangle's code.
function loop () {//Empty canvasctx.clearrect (0,0,canvas.width,canvas.height);//Draw Rectangle Ctx.fillstyle = "Rgba (0,222,255, 0.2 ) "; Ctx.beginpath (); Ctx.moveto (0, CANVAS.HEIGHT/2); Ctx.lineto (Canvas.width, CANVAS.HEIGHT/2); Ctx.lineTo ( Canvas.width, Canvas.height); Ctx.lineto (0, canvas.height); Ctx.lineto (0, CANVAS.HEIGHT/2); Ctx.closepath (); Ctx.fill (); Requestanimframe (loop);}


function loop () {//Empty canvasctx.clearrect (0,0,canvas.width,canvas.height);//Draw Rectangle Ctx.fillstyle = "Rgba (0,222,255, 0.2 ) "; Ctx.beginpath (); Ctx.moveto (0, CANVAS.HEIGHT/2); Ctx.lineto (Canvas.width, CANVAS.HEIGHT/2); Ctx.lineTo ( Canvas.width, Canvas.height); Ctx.lineto (0, canvas.height); Ctx.lineto (0, CANVAS.HEIGHT/2); Ctx.closepath (); Ctx.fill (); Requestanimframe (loop);}
We then change the height of the rectangle in each frame to simulate the shape of the wave, which is actually a periodic movement between the crest and the trough. We assume that both the crest and the trough are 50px, then the height of the rectangle should change from -50px to 50px. To achieve a cyclical effect we take the sine function sin (x) because the value of sin (x) is always between 1 and 1, regardless of how the X value changes. We create a new variable var step = 0 to increment it in each frame, indicating that each frame angle increases once and uses Math.sin () to take his sine value. JS in the radian value of sin, we need to convert the step to radians, var angle = step*math.pi/180; The sine of the angle is multiplied by 50 to get the change in the height of the rectangle. Adds the amount of variation to the y-coordinate of the upper-left and top-right two vertices of a rectangle.

The initial angle is 0var step = 0;function Loop () {ctx.clearrect (0,0,canvas.width,canvas.height); Ctx.fillstyle = "Rgba (0,222,255, 0.2) "///angle Increase once step++;//angle converted to radians var angle = step*math.pi/180;//Rectangle height variation    var deltaheight   = Math.sin (angle) * 50;    Ctx.beginpath ();    The upper left and upper right two vertices of the rectangle are added with a height change of    ctx.moveto (0, canvas.height/2+deltaheight);    Ctx.lineto (Canvas.width, canvas.height/2+deltaheight);    Ctx.lineto (Canvas.width, canvas.height);    Ctx.lineto (0, canvas.height);    Ctx.lineto (0, canvas.height/2+deltaheight);    Ctx.closepath ();    Ctx.fill (); Requestanimframe (loop);}


To run the code:



Change the value of the upper right vertex to the cosine of the angle so that it is out of sync. var deltaheightright = math.cos (angle) * 50;

The initial angle is 0var step = 0;function Loop () {ctx.clearrect (0,0,canvas.width,canvas.height); Ctx.fillstyle = "Rgba (0,222,255, 0.2) "///angle Increase once step++;//angle converted to radians var angle = step*math.pi/180;//Rectangle height variation    var deltaheight   = Math.sin (angle) * 50;    //Rectangle height Change (top right vertex)    var deltaheightright   = Math.Cos (angle) *    Ctx.beginpath ();    Ctx.moveto (0, canvas.height/2+deltaheight);    Top right vertex    ctx.lineto (canvas.width, canvas.height/2+deltaheightright);    Ctx.lineto (Canvas.width, canvas.height);    Ctx.lineto (0, canvas.height);    Ctx.lineto (0, canvas.height/2+deltaheight);    Ctx.closepath ();    Ctx.fill (); Requestanimframe (loop);}


To run the code:


Step4

Turns the top edge of the rectangle into a curve.

In the above code we use LineTo to draw the edges of the rectangle, in order to draw the curve we need

Beziercurveto (cpX1cpY1cpX2cpY2xy)

Function. The starting point for the drawing is the upper-left vertex of the rectangle, and the end point is the top right vertex. The parameters of the Beziercurveto function (cpx1,cpy1) and (CPX2,CPY2) are the control points of the start and end points respectively, and (x, y) are the end points. We set the X value of the two control points to the positive center of the canvas, minus the Y value above the Y value of the starting and ending points (CANVAS.WIDTH/2, canvas.height/2+deltaheight-50), (CANVAS.WIDTH/2, CANVAS.HEIGHT/2+DELTAHEIGHTRIGHT-50), can be adjusted according to the effect.

Ctx.beziercurveto (CANVAS.WIDTH/2, canvas.height/2+deltaheight-50, CANVAS.WIDTH/2, canvas.height/2+ DELTAHEIGHTRIGHT-50, Canvas.width,canvas.height/2+deltaheightright);

Ctx.beginpath (); Ctx.moveto (0, canvas.height/2+deltaheight);//ctx.lineto (Canvas.width, canvas.height/2+ Deltaheightright);//Draw Curve Ctx.beziercurveto (CANVAS.WIDTH/2, canvas.height/2+deltaheight-50, CANVAS.WIDTH/2, CANVAS.HEIGHT/2+DELTAHEIGHTRIGHT-50, Canvas.width, canvas.height/2+deltaheightright); Ctx.lineTo (Canvas.width, Canvas.height); Ctx.lineto (0, canvas.height); Ctx.lineto (0, canvas.height/2+deltaheight); Ctx.closepath ();


Ctx.beginpath (); Ctx.moveto (0, canvas.height/2+deltaheight);//ctx.lineto (Canvas.width, canvas.height/2+ Deltaheightright);//Draw Curve Ctx.beziercurveto (CANVAS.WIDTH/2, canvas.height/2+deltaheight-50, CANVAS.WIDTH/2, CANVAS.HEIGHT/2+DELTAHEIGHTRIGHT-50, Canvas.width, canvas.height/2+deltaheightright); Ctx.lineTo (Canvas.width, Canvas.height); Ctx.lineto (0, canvas.height); Ctx.lineto (0, canvas.height/2+deltaheight); Ctx.closepath ();
To run the code:


Step5

A wave was drawn. We only need to draw 3 different color waves at the same time, and make different wave angles to get the effect.


Defines the color of three different waves var lines = ["Rgba (0,222,255, 0.2)",               "Rgba (157,192,249, 0.2)", "               Rgba (0,168,255, 0.2)"];function Loop () {ctx.clearrect (0,0,canvas.width,canvas.height); step++;//draw 3 different color rectangles for (var j = lines.length-1; J >= 0; j--) { Ctx.fillstyle = lines[j];//The angle of each rectangle is different, each difference between 45 degrees    var angle = (step+j*45) *math.pi/180;    var deltaheight   = Math.sin (angle) *;    var deltaheightright   = Math.Cos (angle) *;    Ctx.beginpath ();    Ctx.moveto (0, canvas.height/2+deltaheight);    Ctx.beziercurveto (CANVAS.WIDTH/2, canvas.height/2+deltaheight-50, CANVAS.WIDTH/2, canvas.height/2+ DELTAHEIGHTRIGHT-50, Canvas.width, canvas.height/2+deltaheightright);    Ctx.lineto (Canvas.width, canvas.height);    Ctx.lineto (0, canvas.height);    Ctx.lineto (0, canvas.height/2+deltaheight);    Ctx.closepath ();    Ctx.fill ();} Requestanimframe (loop);}


To run the code:


Step6

Add a good button and the logo of the HTML code is done.



See all code go to GitHub


If you have any questions or suggestions, please @ued Twitter. I'll respond in time.


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.