canvas實現的變幻線程式碼例項

admin發表於2017-02-13

分享一段程式碼例項,它實現了變幻線效果。

程式碼如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
* {
  margin: 0;
  padding: 0;
}
html {
  overflow: hidden;
}
body {
  background: #000;
}
</style>
<script>
function rnd(n, m) {
  return Math.floor(Math.random() * (m - n) + n)
}
window.onload = function() {
  var oC = document.getElementById("c1");
  var gd = oC.getContext("2d");
 
  var winW = window.innerWidth;
  var winH = window.innerHeight;
  oC.width = winW;
  oC.height = winH;
 
  var r = 255;
  var g = 0;
  var b = 144;
 
  var aPoint = [];
  var N = 5;
  var oldPoint = [];
 
  for (var i = 0; i < N; i++) {
    aPoint<i> = {
      w: 0,
      h: 0,
      x: rnd(0, winW),
      y: rnd(0, winH),
      speedX: rnd(-5, 5),
      speedY: rnd(-5, 5)
    }
  }
  setInterval(function() {
 
    gd.clearRect(0, 0, winW, winH)
 
    for (var i = 0; i < N; i++) {
      drawPoint(aPoint<i>);
 
      aPoint<i>.x += aPoint<i>.speedX;
      aPoint<i>.y += aPoint<i>.speedY;
 
      if (aPoint<i>.x < 0) {
        aPoint<i>.x = 0;
        aPoint<i>.speedX *= -1;
      }
 
      if (aPoint<i>.x > winW) {
        aPoint<i>.x = winW;
        aPoint<i>.speedX *= -1
      }
 
      if (aPoint<i>.y < 0) {
        aPoint<i>.y = 0;
        aPoint<i>.speedY *= -1
 
      }
 
      if (aPoint<i>.y > winH) {
        aPoint<i>.y = winH;
        aPoint<i>.speedY *= -1
      }
 
    }
    console.log(aPoint);
    gd.beginPath();
    gd.moveTo(aPoint[0].x, aPoint[0].y)
    for (var i = 1; i < N; i++) {
      gd.lineTo(aPoint<i>.x, aPoint<i>.y);
    }
    gd.strokeStyle = 'rgba(' + r + ',' + g + ',' + b + ',1)';
    gd.closePath();
    gd.stroke();
    var arr = [];
 
 
    for (var i = 0; i < N; i++) {
      arr.push({
        x: aPoint<i>.x,
        y: aPoint<i>.y
      })
    }
    oldPoint.push(arr);
    while (oldPoint.length > 20) {
      oldPoint.shift()
    }
    for (var i = 0; i < oldPoint.length; i++) {
      gd.beginPath();
      gd.moveTo(oldPoint<i>[0].x, oldPoint<i>[0].y)
      for (var j = 1; j < N; j++) {
        gd.lineTo(oldPoint<i>[j].x, oldPoint<i>[j].y);
      }
      gd.closePath();
      var opacity = i / oldPoint.length;
 
      gd.strokeStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + opacity + ')'
      gd.stroke();
    }
 
 
  }, 16)
 
  function drawPoint(p) {
    gd.fillStyle = '#fff';
    gd.fillRect(p.x, p.y, p.w, p.h);
    gd.strokeRect(p.x, p.y, p.w, p.h);
  }
};
</script>
</head>
<body>
<canvas id="c1"></canvas>
</body>
</html>

相關文章