本文实例讲述了基于canvas实现的钟摆效果。分享给大家供大家参考,具体如下:

运行效果截图如下:

基于canvas实现的钟摆效果完整实例

具体代码如下:

<!DOCTYPE html>
<html>
 <head>
  <title>demo</title>
  <style type="text/css">
   body {
    margin:0; padding:0;
   }
   #canvas {
    border:2px solid gray; box-shadow:0px 0px 2px 2px #494949;
   }
  </style>
 </head>
 <body>
  <canvas id="canvas" width="500px" height="500px"></canvas>
  <script type="text/javascript">
   var canvas = document.getElementById("canvas");
   var ctx = canvas.getContext("2d");
   var r = 250;
   var colorList = "abcdefABCDEF0123456789".split("");
   var colorListLength = colorList.length;
   var color = function() {
    var _color = "#";
    for(var i=0; i<6; i++) {
     _color += colorList[Math.round(Math.random()*colorListLength)];
    }
    return _color;
   };
   var createArc = function(attrs) {
    ctx.save();
    ctx.beginPath();
    ctx.fillStyle = attrs.color || color();
    ctx.arc(attrs.x, attrs.y, attrs.r, 0, Math.PI*2);
    ctx.closePath();
    ctx.fill();
    ctx.restore();
   };
   var createLine = function(from, to) {
    ctx.save();
    ctx.beginPath();
    ctx.moveTo(from.x, from.y);
    ctx.lineTo(to.x, to.y);
    ctx.stroke();
    ctx.closePath();
    ctx.restore();
   }
   var createAll = function(to) {
    createArc({x: 250, y: 0, r: 10, color: "black"});
    createArc({x: to.x, y: to.y, r: 20, color: "black"});
    createLine({x: 250, y: 0}, {x: to.x, y: to.y});
   };
   var minAngle = 0;
   var maxAngle = Math.PI;
   var addAngle = Math.PI/24;
   var angle = minAngle;
   var mode = "left";
   var interval = setInterval(function() {
    var y = Math.sin(angle)*r+200;
    var x = Math.cos(angle)*r+250;
    switch(mode) {
     case "left":
      ctx.clearRect(0, 0, 500, 500);
      createAll({x: x, y: y});
      angle += addAngle;
      if(angle > maxAngle) {
       mode = "right";
       angle -= addAngle;
       return;
      }
      break;
     case "right":
      ctx.clearRect(0, 0, 500, 500);
      createAll({x: x, y: y});
      angle -= addAngle;
      if(angle < minAngle) {
       mode = "default";
       angle += addAngle;
       return;
      }
      break;
     case "default":
      createAll({x: x, y: y});
      angle += addAngle;
      if(angle > maxAngle) {
       mode = "left";
       angle = minAngle;
       return;
      }
      break;
    }
   }, 50);
  </script>
 </body>
</html>

更多关于js特效相关内容感兴趣的读者可查看本站专题:《jQuery动画与特效用法总结》及《jQuery常见经典特效汇总》

希望本文所述对大家JavaScript程序设计有所帮助。

标签:
canvas,钟摆效果

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
无争山庄资源网 Copyright www.whwtcm.com

评论“基于canvas实现的钟摆效果完整实例”

暂无“基于canvas实现的钟摆效果完整实例”评论...