基于canvas实现的钟摆效果完整实例_Javascript教程-查字典教程网
基于canvas实现的钟摆效果完整实例
基于canvas实现的钟摆效果完整实例
发布时间:2016-12-30 来源:查字典编辑
摘要:本文实例讲述了基于canvas实现的钟摆效果。分享给大家供大家参考,具体如下:运行效果截图如下:具体代码如下:demobody{margin...

本文实例讲述了基于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>

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

相关阅读
推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
  • 大家都在看
  • 小编推荐
  • 猜你喜欢
  • 最新Javascript教程学习
    热门Javascript教程学习
    编程开发子分类