dimanche 10 mai 2020

How can I end a requestanimationFrame with a function?

I have the following code in which I have set a requestanimationFrame and I want to end it by calling the function draw2. It's a beginner's animation based on the single ball bouncing on the wall.

 <body>               
    // canvas creation
var x =290;
var y=320;
var xdir=1;
var hit =0;


    // select directions
function select () {
    if (x ==950 || x==0){

    xdir=-1* xdir}


        if (xdir==1) {
        x=x+5;
        }
        else 
        {
        x=x-5;
        }

    requestAnimationFrame(draw1);

function draw1()  { 
    ctx.clearRect(0, 0, 1000, 800 );
    ctx.beginPath();
                  var draw1=ctx.arc(x,y,5,0,2*Math.PI);  
                  ctx.strokeStyle="black";
                  ctx.stroke();
                  ctx.fillStyle="darkgrey";
                  ctx.fill();             

        //draw cowboy
            // body
    ctx.beginPath();
    ctx.lineWidth = 10;
    ctx.strokeStyle = "black";
    ctx.lineCap = "square";
    ctx.moveTo(100, 300);
    ctx.lineTo(100, 600);
    ctx.stroke();

    // hand 
    ctx.beginPath();
    ctx.strokeStyle = " black";
    ctx.lineCap = "round";
    ctx.moveTo(100, 350);
    ctx.lineTo(250, 350);
    ctx.stroke();


    //gun
    ctx.beginPath();
    ctx.strokeStyle = "darkgrey";
    ctx.lineWidth=10;
    ctx.moveTo(250, 350);
    ctx.lineTo(250, 320);
    ctx.lineTo(290, 320);
    ctx.stroke()

    //head
    ctx.beginPath();
    ctx.fillStyle = "black";
    ctx.lineWidth=5;
    ctx.arc(100,280,50,0,2*Math.PI);    
    ctx.fill(); 

        } 



     function draw2() {
      ctx.clearRect(0, 0, 1000, 800 );
    ctx.beginPath();

         //draw dead cowboy
            // body

    var draw2=ctx.lineWidth = 10;
    ctx.strokeStyle = "black";
    ctx.lineCap = "square";
    ctx.moveTo(300, 600);
    ctx.lineTo(100, 600);
    ctx.stroke();


    //head
    ctx.beginPath();
    ctx.fillStyle = "black";
    ctx.lineWidth=5;
    ctx.arc(340,580,50,0,2*Math.PI);    
    ctx.fill();

     } 

    requestAnimationFrame(draw1);
        setInterval(select, 20);

    </script>
</body

>

I try to set an if statement like this:

if (x==120) {
            hit=1;
        }

        if (hit==1){
            alert ("This was a mistake!");
            draw2();
    }

but when I try this the animation disappears completely from the canvas. I think I have the correct guidance but I can't put them together.

Aucun commentaire:

Enregistrer un commentaire