0

我正在构建像城市集团这样的 html5 游戏我想像 Pendulum 一样移动抢劫图片

绘图功能

function draw(){
ctx.save();
ctx.translate(20,0);
ctx.translate(box1.width/2,0);
ctx.rotate(val*(Math.PI/180));
ctx.drawImage(box1,box1.X,box1.Y);
ctx.restore();


}

现在我已经准备好旋转方法我试着按照我说的那样移动它

function boxPendolAnim(){

loop1 = setInterval(function(){
val =  val -0.1;

},200);

setInterval(function(){
if (val <=-2) {
clearInterval(loop1);
setInterval(function(){
val = val +0.1;
},200);

}; 

},200);

} 

但它只工作一次就停止了我想要像钟摆一样移动图片的功能

4

1 回答 1

1

在您的代码中:

  • 只需使用 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>
于 2013-10-18T18:51:15.657 回答