基于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实现的钟摆效果完整实例 的全部内容, 来源链接: utcz.com/z/325613.html

回到顶部