Use Canvas to add a dynamic background for a webpage

Source: Internet
Author: User

Recently, I have just received a task of creating a homepage for the Public Account "Play with Sanlitun. Considering that the page is only viewed on the mobile phone, and the mobile phone supports canvas very well, we plan to use canvas for different animations.

First, let's take a look.


To achieve this kind of animation, the normal CSS3 can only use Canvas. Fortunately, using canvas is also very simple.

Step1.

Create a new <canvas> element and place it below all buttons and logos to avoid blocking the previous element.

<canvas id="canvas" style="position:absolute;top:0px;left:0px;z-index:1;"></canvas>

Set the width and height of the Canvas to the width and height of its parent element to fill it with its parent element. You can also directly use window. innerHeight and window. innerWidth. Fill it with the whole screen.

var canvas = document.getElementById('canvas');var ctx = canvas.getContext('2d');canvas.width = canvas.parentNode.offsetWidth;canvas.height = canvas.parentNode.offsetHeight;
Step2.

Draw a rectangle filled with half a screen in the canvas.

We only need to find the coordinates of the four fixed points of the rectangle, use the Canvas to draw the path and fill the path. The four points are:

(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 the color ctx. fillStyle = "rgba (0,222,255, 0.2)"; // start to draw the ctx path. beginPath (); // ctx in the upper left corner. moveTo (0, canvas. height/2); // ctx in the upper right corner. lineTo (canvas. width, canvas. height/2); // ctx in the lower right corner. lineTo (canvas. width, canvas. height); // ctx in the lower left corner. lineTo (0, canvas. height); // ctx in the upper left corner. lineTo (0, canvas. height/2); // closed path ctx. closePath (); // fill in the ctx path. fill ();

Run the Code:


Step3.

Let the rectangle move. To make an animation, we need to constantly clear the canvas and re-draw new rectangles, just like 24 images per second for a movie. We create a new loop function to draw the image of each frame, and use requestAnimFrame to tell the browser to use loop to draw each frame.

// If the browser supports requestAnimFrame, use requestAnimFrame; otherwise, use setTimeoutwindow. requestAnimFrame = (function () {return window. requestAnimationFrame | window. webkitRequestAnimationFrame | window. required requestanimationframe | function (callback) {window. setTimeout (callback, 1000/60) ;};} (); function loop () {requestAnimFrame (loop) ;} loop ();

Put the code of the previously drawn rectangle in the loop, and clear all the images in the canvas before drawing the code of the rectangle.
Function loop () {// clear canvasctx. clearRect (0, 0, canvas. width, canvas. height); // draw a 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 );}
Next, we will change the height of the rectangle in each frame to simulate the form of the wave. The wave is actually a periodic movement between the wave peak and the valley. We assume that the peak and valley are both 50px, so the height of the rectangle should be between-50px and 50px. To achieve the cyclical effect, we use the sin (x) sine function, because the value of sin (x) is always between-1 and 1 no matter how the value of x changes. We create a variable var step = 0 to increase itself in each frame, indicating that the angle of each frame is increased for one time, and use Math. sin () to obtain its sine value. In JS, the sin uses the radian value. We need to convert the step to the radian value. var angle = step * Math. PI/180; multiply the sine value of the angle by 50 to obtain the variation of the rectangle height. Add the variation value to the y coordinate of the top left and top right vertices of the 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)"; // increase the angle by step ++. // convert the angle to a radian var angle = step * Math. PI/180; // the variation of the rectangle height var deltaHeight = Math. sin (angle) * 50; ctx. beginPath (); // Add the height change ctx to the top left and top right vertices of the rectangle. 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 );}

Run the Code:



Change the variation value of the top right vertex to the cosine of the angle so that the Left and Right vertices are not synchronized. 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)"; // increase the angle by step ++. // convert the angle to a radian var angle = step * Math. PI/180; // the variation of the rectangle height var deltaHeight = Math. sin (angle) * 50; // the variation of the rectangle height (top right vertex) var deltaHeightRight = Math. cos (angle) * 50; 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 );}

Run the Code:


Step 4

Turns the top side of the rectangle into a curve.

In the above Code, we use lineTo to draw the edge of a rectangle. To draw a curve, we need

bezierCurveTo(cpX1, cpY1, cpX2, cpY2, x, y)
Function. The starting point of the painting is the top left vertex of the rectangle, and the ending point is the top right vertex. In the bezierCurveTo function parameters (cpX1, cpY1) and (cpX2, cpY2) are the control points of the start and end points, respectively, (x, y) is the end point. We set the x values of the two control points to the center of the canvas, and the y value minus 50 on the y values of the start and end 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); // draws the ctx curve. 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 ();
Run the Code:


Step 5

A wave has been drawn. We only need to draw three waves of different colors at the same time, and make the angle of different waves different to get the expected effect.

// Define three different wave colors 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 three rectangles of different colors for (var j = lines. length-1; j> = 0; j --) {ctx. fillStyle = lines [j]; // The angle of each rectangle is different. The difference between each rectangle is 45 degrees var angle = (step + j * 45) * Math. PI/180; var deltaHeight = Math. sin (angle) * 50; var deltaHeightRight = Math. cos (angle) * 50; 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 );}

Run the Code:


Step 6

The HTML code for adding buttons and logos is complete.



Go to Github to view all the code.


If you have any questions, ask Weibo @ UED Tianji. I will reply 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.