Search code examples
javascripthtml5-canvas2d-games

move the canvas image like Pendulum


i`m building html5 games like city blocs i want to move rob picture like Pendulum

the drwing function

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();


}

now i have rotation method ready i tried this to move it as i said

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);

} 

but it work only once no more then stopped i want function to move the picture like pendulum


Solution

  • In your code:

    • Just use 1 setInterval.
    • In the function executed by setInterval, increase the angle until it is at your desired maximum and then decrease the angle.

    This is an example of an image in pendulum motion:

    enter image description here

    Here’s code and a Fiddle: 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>