用canvas实现简单的下雪效果(附代码)


当前第2页 返回上一页

完整代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

           <!DOCTYPE html>

<head>

  <style>

    body {

      background-color: #102a54;

    }

  </style>

</head>

<body>

  <canvas id='sky'></canvas>

  <script src="snow.js"></script>

</body>

 

</html>

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

window.onload = function () {

  // get the canvas and context

  var canvas = document.getElementById('sky');

  var ctx = canvas.getContext('2d');

 

  // set canvas dims to window height and width

  var W = window.innerWidth;

  var H = window.innerHeight;

  canvas.width = W;

  canvas.height = H;

 

  // generate snowflakes and apply attributes

  var flakesCount = 100;

  var flakes = []; // flake instances

 

  // loop through the empty flakes and apply attributes

  for (var i = 0; i < flakesCount; i++) {

    flakes.push({

      x: Math.random() * W,

      y: Math.random() * H,

      r: Math.random() * 5 + 2, // 2px - 7px

      d: Math.random() + 1

    });

  }

 

  // draw flakes onto canvas

  function drawFlakes() {

    ctx.clearRect(0, 0, W, H);

    ctx.fillStyle = '#fff';

    ctx.beginPath();

    for (var i = 0; i < flakesCount; i++) {

      var flake = flakes[i];

      ctx.moveTo(flake.x, flake.y);

      ctx.arc(flake.x, flake.y, flake.r, 0, Math.PI * 2, true);

    }

    ctx.fill();

    moveFlakes();

  }

 

  var angle = 0;

 

  function moveFlakes() {

    angle += 0.01;

    for (var i = 0; i < flakesCount; i++) {

      var flake = flakes[i];

      flake.y += Math.pow(flake.d, 2) + 1;

      flake.x += Math.sin(angle) * 2;

 

      if (flake.y > H) {

        flakes[i] = { x: Math.random() * W, y: 0, r: flake.r, d: flake.d };

      }

    }

  }

 

  setInterval(drawFlakes, 25);

}

以上就是用canvas实现简单的下雪效果(附代码)的详细内容,更多文章请关注木庄网络博客

返回前面的内容

相关阅读 >>

html marquee标签如何设置图片滚动?marquee标签的图片滚动代码实例

vue刷新404的问题解决方法

html中怎么加img路径

html怎么去掉超链接的下划线

js保留两位小数的函数有哪些

详细介绍精选HTML5/css3动画应用源码分享

360浏览器不能运行javascript怎么办

小总结 javascript 开发中常见错误解决

html怎么隐藏div元素

css如何实现任意角度的扇形(代码示例)

更多相关阅读请进入《HTML5》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...