canvas實現點選產生放射性效果程式碼例項

螞蟻小編發表於2017-02-27
下面的程式碼實現了點選頁面的任何一個位置都會產生放射性效果的功能。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
.bg {
  background: #000;
  overflow: hidden;
}
</style>
</head>
<body class="bg">
<canvas id="canvas-club"></canvas>
<script>
var c = document.getElementById("canvas-club");
var ctx = c.getContext("2d");
var w = c.width = window.innerWidth;
var h = c.height = window.innerHeight;
var clearColor = 'rgba(0, 0, 0, .1)';
 
function Rippling() {}
Rippling.prototype = {
  init: function(posX, posY) {
    this.x = posX;
    this.y = posY;
    this.w = 3;
    this.h = 2;
    this.vw = 1;
    this.vh = 1;
    this.a = 1;
    this.va = .96;
  },
  draw: function() {
    ctx.beginPath();
    ctx.moveTo(this.x, this.y - this.h / 2);
    ctx.bezierCurveTo(
      this.x + this.w / 2, this.y - this.h / 2,
      this.x + this.w / 2, this.y + this.h / 2,
      this.x, this.y + this.h / 2);
    ctx.bezierCurveTo(
      this.x - this.w / 2, this.y + this.h / 2,
      this.x - this.w / 2, this.y - this.h / 2,
      this.x, this.y - this.h / 2);
    ctx.strokeStyle = 'hsla(180, 100%, 50%, ' + this.a + ')';
    ctx.stroke();
    ctx.closePath();
    this.update();
  },
  update: function() {
    if (this.a > .03) {
      this.w += this.vw;
      this.h += this.vh;
      if (this.w > 1) {
        this.a *= this.va;
        this.vw *= .98;
        this.vh *= .98;
      }
    } else {
      ctx.clearRect(0, 0, c.width, c.height);
      return false;
    }
  }
};
 
function anim() {
  ctx.fillStyle = clearColor;
  ctx.fillRect(0, 0, w, h);
  r.draw();
  requestAnimationFrame(anim);
};
var r = new Rippling();
window.onclick = function(event) {
  function getMousePos(event) {
    var e = event || window.event;
    var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
    var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
    var x = e.pageX || e.clientX + scrollX;
    var y = e.pageY || e.clientY + scrollY;
    return {
      'x': x,
      'y': y
    };
  }
  r.init(getMousePos().x, getMousePos().y);
}
anim();
</script>
</body>
</html>

相關文章