在您的代码中:
- 只需使用 1 个 setInterval。
- 在 setInterval 执行的函数中,增加角度直到达到所需的最大值,然后减小角度。
这是摆幅运动图像的示例:

这是代码和小提琴:http: //jsfiddle.net/m1erickson/n9KrM/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" />
<script src="http://code.jquery.com/jquery.min.js"></script>
<style>
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var rotation=0; // start at horizontal
var direction=Math.PI/60; // 3 degrees change each loop
var box1=new Image();
box1.onload=function(){
setInterval(go,40);
}
box1.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house-icon.png";
function go(){
// set the new rotation
rotation+=direction;
if(rotation>Math.PI || rotation<0){
direction=-direction;
rotation+=direction;
}
ctx.clearRect(0,0,canvas.width,canvas.height);
draw();
}
function draw(){
ctx.save();
ctx.translate(120,40);
ctx.rotate(rotation);
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(40,0);
ctx.rect(40,-15,30,30);
ctx.stroke();
ctx.drawImage(box1,0,0,box1.width,box1.height,40,-15,30,30);
ctx.restore();
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>