本文實例講述了基於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程序設計有所幫助。