用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实现简单的下雪效果(附代码)的详细内容,更多文章请关注木庄网络博客

返回前面的内容

相关阅读 >>

HTML5画布的详细介绍

html怎么去掉元素的边框

javascript web workers的构建块及5个使用场景

html怎样格式化输出json数据

javascript中如何使用spread运算符(...)?8种方法介绍

HTML5+css3实现无插件拖拽上传图片(支持预览与批量)的详情介绍

浏览器中5种常用的事件解析

学js需要什么基础?

HTML5 touch事件实现触屏页面上下滑动(一)

javascript怎样验证手机号码

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




打赏

取消

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

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

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

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

评论

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