canvas实现雷达扫描效果

2020-06-22  本文已影响0人  Lily_FJ

效果图:



代码如下:

 <style>
    * {
      padding: 0;
      margin: 0;
    }
    .container {
      width: 300px;
      height: 300px;
      position: absolute;
      left: 50%;
      top: 50%;
      margin-left: -150px;
      margin-top: -150px;
    }
    #myCanvas {
      opacity: 0.7;
    }
  </style>

<div class="container">
    <canvas id="myCanvas"></canvas>
  </div>
  <script>
    var nTime = 2000;//完成一圈所需的毫秒数
    var nStart = 0;
    var dCanvas = $("#myCanvas")[0];
    var oCtx = dCanvas.getContext("2d");
    var rander = function (timeStamp) {
      if (!nStart) {
        nStart = timeStamp;
      }
      var nDiffTime = timeStamp - nStart;
      oCtx.save();
      oCtx.beginPath();
      oCtx.arc(150, 150, 150, -1 / 2 * Math.PI, -1 / 2 * Math.PI + 2 * Math.PI * nDiffTime / nTime);
      oCtx.lineTo(150, 150);
      oCtx.closePath();
      oCtx.clip();
      oCtx.drawImage(img, 0, 0, 300, 300);
      oCtx.restore();
      if (nDiffTime <= nTime) {
        requestAnimationFrame(rander);
      }
    };
    var img = new Image();
    img.src = 'img/randar.jpg';
    img.onload = function () {
      var jqContainer = $('.container');
      dCanvas.width = jqContainer.width();
      dCanvas.height = jqContainer.height();
      requestAnimationFrame(rander);
    };
  </script>

好记性不如烂笔头,总结和记录工作学习中的点点滴滴,如有不对之处还请指教。

参考
[1] js实现雷达扫描效果
[2] canvas实现"雷达扫描"效果
[3] 基于canvas实现的旋转时间圆点
[4] canvas动态画圆弧及requestAnimationFrame

上一篇下一篇

猜你喜欢

热点阅读