荟萃馆

位置:首页 > 设计 > 网页设计

基于html5 canvas实现漫天飞雪效果的方法

导语:基于html5 canvas实现漫天飞雪效果的方法,你懂吗?下面的`是本站小编为大家搜集的基于html5 canvas实现漫天飞雪效果的方法,运行该实例可以看到很棒的下雪效果。如下图所示:

基于html5 canvas实现漫天飞雪效果的方法

  主要代码如下:

  代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<a href=""></a>">

<html xmlns="<a href=""></a>">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />

<title>漫天飞雪</title>

<style type="text/css">

* {margin: 0; padding: 0;}</p> <p>body {

/*You can use any kind of background here.*/

background: #6b92b9;

}

canvas {

display: block;

}

</style>

</head></p> <p><body></p> <p><p style=" background:#6b92b9; width:100%; height:2000px;" ></p>

<canvas id="canvas" style="position:fixed; top:0px;left:0px;z-index:80;pointer-events:none;"></canvas></p> <p><script>

ad = function(){

//canvas init

var canvas = lementById("canvas");

var ctx = ontext("2d");

//canvas dimensions

var W = rWidth;

var H = rHeight;

h = W;

ht = H;

//snowflake particles

var mp = 3000; //max particles

var particles = [];

for(var i = 0; i < mp; i++)

{

({

x: om()*W, //x-coordinate

y: om()*H, //y-coordinate

r: om()*3+1, //radius

d: om()*mp //density

})

}

//Lets draw the flakes

function draw()

{

rRect(0, 0, W, H);

Style = "rgba(255, 255, 255, 0.8)";

/* Style = "#FF0000";*/

nPath();

for(var i = 0; i < mp; i++)

{

var p = particles[i];

To(p.x, p.y);

(p.x, p.y, p.r, 0, *2, true);

}

();

update();

}

//Function to move the snowflakes

//angle will be an ongoing incremental flag. Sin and Cos functions will be applied to it to create vertical and horizontal movements of the flakes

var angle = 0;

function update()

{

angle += 0.01;

for(var i = 0; i < mp; i++)

{

var p = particles[i];

//Updating X and Y coordinates

//We will add 1 to the cos function to prevent negative values which will lead flakes to move upwards

//Every particle has its own density which can be used to make the downward movement different for each flake

//Lets make it more random by adding in the radius

p.y += (angle+p.d) + 1 + p.r/2;

p.x += (angle) * 2;

//Sending flakes back from the top when it exits

//Lets make it a bit more organic and let flakes enter from the left and right also.

if(p.x > W || p.x < 0 || p.y > H)

{

if(i%3 > 0) //66.67% of the flakes

{

particles[i] = {x: om()*W, y: -10, r: p.r, d: p.d};

}

else

{

//If the flake is exitting from the right

if((angle) > 0)

{

//Enter fromth

particles[i] = {x: -5, y: om()*H, r: p.r, d: p.d};

}

else

{

//Enter from the right

particles[i] = {x: W+5, y: om()*H, r: p.r, d: p.d};

}

}

}

}

}

//animation loop

setInterval(draw, 15);

}

</script>

</body>

</html>

代码分析如下:

这行代码改变雪花半径大小:

代码如下:

r: om()*3+1, //radius

这行代码改变雪花下落速度:

代码如下:

setInterval(draw, 15);

这行值改变雪花密度:

代码如下:

var mp = 3000; //max particles