Home > Web Front-end > H5 Tutorial > h5canvas implements special effects code for falling snowflakes

h5canvas implements special effects code for falling snowflakes

零下一度
Release: 2017-05-17 14:23:29
Original
5283 people have browsed it

This article mainly introduces in detail HTML5 canvas to achieve the special effect of falling snowflakes, and the effect is fascinating and very realistic animation effect. Interested friends can refer to it

I have seen many displays on the Internet showing the effect of html5 snowflakes flying, which is indeed very fascinating. I believe that everyone is as excited as me and is also very curious and wants to study how to implement the code; although many places also I can download these source codes, but I don’t know other people’s ideas and analysis of difficulties when making such animations.

I just happened to study a little these days, and I took advantage of the time to dissect it step by step from demand analysis, knowledge points, and programming. If I try to make a fool of myself in front of you, please don’t laugh. .

The final rendering is as follows:

Figure 1

1. Requirements analysis

1. Circular snowflakes

In this example, the shape of the snowflakes is circular

2. The number of snowflakes is fixed

Carefully observe the number of white snowflakes according to Figure 1. During the falling process, The number of snowflakes in the picture should be fixed. This requirement needs to be obtained through our observation and analysis. This is consistent with the scene we see in real life where snowflakes are flying all over the sky.

3. The size of snowflakes is inconsistent

Each snowflake has a different size, which means that the radius of the snowflake is random. This is also consistent with the scene where we see snowflakes flying all over the sky in real life.

4. The position of the snowflakes is moving

Snowflakes fall, and naturally their positions are also moving.

2. Knowledge points

1. Use Html5 Canvas+JavaScript to draw a circle - forming a circular snowflake

In Html5 , you need to use Canvas and draw a circle with JavaScript to form a circular snowflake—arc(x,y,r,start,stop);

2. Random numbers—generate circles with different radii and coordinates Snowflake

In this example, when the web page is loaded for the first time, a certain number of snowflakes with different radii and positions need to be generated, so the radius and coordinates are random numbers; while the snowflakes are falling, their radius remains unchanged and their coordinates remain unchanged. Changes within a certain range, so the coordinates are also random numbers at this time - Math.random()

3. Programming

1. Preparation

Put a canvas and set the background color of the entire body to black

HTML code:

XML/HTML CodeCopy content to clipboard

<canvas id="mycanvas">
    您的浏览器不支持canvas画布   
</canvas>
Copy after login

CSS Code:

CSS CodeCopy content to clipboard

* {   
    margin: 0;   
    padding: 0;   
}   
#mycanvas {   
    background: black;   
}
Copy after login

The effect at this time is as follows:

Note: canvas has an initialized height and width by default, so there is no need to worry about it

2. The canvas fills the screen

The JavaScript code is as follows:

JavaScript CodeCopy the content to the clipboard

//获取mycanvas画布   
    var can = document.getElementById("mycanvas");   
    var ctx = can.getContext("2d");   
    //画布宽度   
    var wid = window.innerWidth;   
    //画布高度   
    var hei = window.innerHeight;   
    can.width=wid;   
    can.height=hei;
Copy after login

The effect at this time is as follows:

3. Initialization generates a fixed number of snowflakes

According to our above demand analysis And interpretation of knowledge points, first of all, the number of snowflakes is fixed, so we need to define a variable var snow = 100; here it is assumed that the number of snowflakes is 100,;

When generating snowflakes, each Each snowflake has a different radius and position. We regard each snowflake as an object. Then the attributes of this object include: radius and coordinates (X, Y). Then a snowflake object can be written as var snowOject={x:1,y: 10,r:5}, here represents a circular snowflake with coordinates (1,10) and radius 5; in this example, since the radius and coordinates are random numbers, Math.random() is used to generate 100 snowflakes respectively. Generate radius and coordinates (X, Y);

We have 100 snowflakes here, so in order to facilitate subsequent operations, we use an array to save these 100 snowflake objects.

The JavaScript code is as follows:

JavaScript CodeCopy the content to the clipboard

//雪花数目   
var snow = 100;   
//雪花坐标、半径   
var arr = []; //保存各圆坐标及半径   
for (var i = 0; i < snow; i++) {   
arr.push({   
x: Math.random() * wid,   
y: Math.random() * hei,   
r: Math.random() * 10 + 1   
})   
}
Copy after login

4. Draw snowflakes

上面我们已经将100个雪花半径、坐标(X、Y)生成,下面就是循环使用canvas画出雪花了(这里就是画圆),这里定义一个函数

JavaScript代码如下:

JavaScript Code复制内容到剪贴板

//画雪花   
function DrawSnow() {   
    ctx.fillStyle="white";   
    ctx.beginPath();   
    for (var i = 0; i < snow; i++) {   
        var p = arr[i];   
        ctx.moveTo(p.x,p.y);   
        ctx.arc(p.x,p.y,p.r,0,2*Math.PI,false);   
    }   
    ctx.fill();   
  
    ctx.closePath();
Copy after login

然后调用 DrawSnow()函数,效果如下:

可以尝试多次刷新网页看是否会生成不同大小、位置的雪花(正常情况下是可以的),做到这里就已经接近最终效果了

注意:由于这里需要绘制100个圆,所以每当画一个圆时重新定义绘制开始坐标即:ctx.moveTo(p.x,p.y);否则会出现异样效果,不信可以试试呀

5、雪花飘动

上面我们已经画出100个雪花,可惜只能依靠刷新网页才能看到变化效果,但是我们需要实现的是雪花不停的移动位置。

首先我们需要借助setInterval函数不停的重画雪花,这里间隔时间为50毫秒:setInterval(DrawSnow,50);

同时每一朵雪花的坐标(X、Y)需要不停的改变(在一定幅度内),我们这里的雪花是从左上方飘落到右下方,所以每朵X、Y坐标值都在不停的增大,那我们用一个函数SnowFall()定义雪花飘过规则

该函数代码如下:

JavaScript Code复制内容到剪贴板

//雪花飘落   
function SnowFall() {   
    for (var i = 0; i < snow; i++) {   
        var p = arr[i];   
        p.y += Math.random() * 2 + 1;   
        if (p.y > hei) {   
            p.y = 0;   
        }   
        p.x += Math.random() * 2 + 1;   
        if (p.x > wid) {   
            p.x = 0;   
    <span style="white-space:pre">    </span>}   
    }   
}
Copy after login

然后将该函数放入DrawSnow()执行,注意:我们每隔50毫毛重画雪花,必须擦除画布,所以DrawSnow()函数体内必须在前面执行clearRect()函数,即:ctx.clearRect(0, 0, wid, hei);

此时DrawSnow函数定义如下:

JavaScript Code复制内容到剪贴板

//画雪花   
function DrawSnow() {   
    ctx.clearRect(0, 0, wid, hei);   
    ctx.fillStyle = "white";   
    ctx.beginPath();   
    for (var i = 0; i < snow; i++) {   
        var p = arr[i];   
        ctx.moveTo(p.x, p.y);   
        ctx.arc(p.x, p.y, p.r, 0, 2 * Math.PI, false);   
    }   
    ctx.fill();   
    SnowFall();   
    ctx.closePath();   
}
Copy after login

最后执行setInterval(DrawSnow, 50);

OK,经过我们上述步骤,小伙伴们是否已经对整个过程及技术实现很清晰了。

完整代码如下(大家可以直接复制到自己项目中执行,测试下效果):

XML/HTML Code复制内容到剪贴板

<!DOCTYPE html>  
<html>  
    <head>  
        <meta charset="utf-8" />  
        <title></title>  
        <script src="js/jquery-1.8.3.min.js"></script>  
        <style type="text/css">  
            * {   
                margin: 0;   
                padding: 0;   
            }   
               
            #mycanvas {   
                background: black;   
            }   
        </style>  
    </head>  
  
    <body>  
        <canvas id="mycanvas">  
            您的浏览器不支持canvas画布   
        </canvas>  
        <script>  
            //获取mycanvas画布   
            var can = document.getElementById("mycanvas");   
            var ctx = can.getContext("2d");   
            //画布宽度   
            var wid = window.innerWidth;   
            //画布高度   
            var hei = window.innerHeight;   
            can.width = wid;   
            can.height = hei;   
            //雪花数目   
            var snow = 100;   
            //雪花坐标、半径   
            var arr = []; //保存各圆坐标及半径   
            for (var i = 0; i < snow; i++) {   
                arr.push({   
                    x: Math.random() * wid,   
                    y: Math.random() * hei,   
                    r: Math.random() * 10 + 1   
                })   
            }   
            //画雪花   
            function DrawSnow() {   
                ctx.clearRect(0, 0, wid, hei);   
                ctx.fillStyle = "white";   
                ctx.beginPath();   
                for (var i = 0; i < snow; i++) {   
                    var p = arr[i];   
                    ctx.moveTo(p.x, p.y);   
                    ctx.arc(p.x, p.y, p.r, 0, 2 * Math.PI, false);   
                }   
                ctx.fill();   
                SnowFall();   
                ctx.closePath();   
            }   
            //雪花飘落   
            function SnowFall() {   
                for (var i = 0; i < snow; i++) {   
                    var p = arr[i];   
                    p.y += Math.random() * 2 + 1;   
                    if (p.y > hei) {   
                        p.y = 0;   
                    }   
                    p.x += Math.random() * 2 + 1;   
                    if (p.x > wid) {   
                        p.x = 0;   
                    }   
                }   
            }   
            setInterval(DrawSnow, 50);   
        </script>  
    </body>  
  
</html>
Copy after login

【相关推荐】

1. 特别推荐“php程序员工具箱”V0.1版本下载

2. h5 Canvas中Fill 与Stroke文字效果实现实例

3. 分享用canvas实现水流和水池动画的代码

The above is the detailed content of h5canvas implements special effects code for falling snowflakes. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template