Skip to content Skip to sidebar Skip to footer

Animating Images With Javascript

I am trying to make the images race each other and once one of the images passes the finish line display the winner. I have some old code I used for the animation but i don't know

Solution 1:

Here is some of your code refactored to race car images:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

// game varsvar redRectangle={x:5,y:40,width:62,height:21};
var goldRectangle={x:5,y:75,width:62,height:21};
var finishX=450;

// animation varsvar nextTime=0;
var delay=1000/60;

// image vars and call start() when all images are loadedvar red=newImage();
red.onload=start;
red.src='https://dl.dropboxusercontent.com/u/139992952/multple/car1.png';
var gold=newImage();
gold.onload=start;
gold.src='https://dl.dropboxusercontent.com/u/139992952/multple/car2.png';
var imageCount=2;
functionstart(){
    // return if all the images aren't loadedif(--imageCount>0){return;}
    // start the animation looprequestAnimationFrame(animate);    
}

functionanimate(time){

    // has the desired time elapsed?if(time<nextTime){requestAnimationFrame(animate);return;}
    nextTime=time+delay;

    // update the car positions
    redRectangle.x+=Math.random()*5;
    goldRectangle.x+=Math.random()*5;

    // draw the current scene
    ctx.clearRect(0,0,canvas.width,canvas.height);
    drawFinishLine(ctx);
    drawRedRect(redRectangle, ctx);
    drawgoldRect(goldRectangle, ctx);    

    // request another animation loop
    hasRedWon=redRectangle.x+redRectangle.width>finishX;
    hasGoldWon=goldRectangle.x+goldRectangle.width>finishX;
    
    // alert if race is overif(hasRedWon){ alert('Red wins'); return; }
    if(hasGoldWon){ alert('Gold wins'); return; }

    // race is still going, request another animation looprequestAnimationFrame(animate);
}

// draw images instead of rectsfunctiondrawRedRect(redRectangle, ctx){
    ctx.drawImage(red, redRectangle.x, redRectangle.y, redRectangle.width, redRectangle.height);
}
// draw images instead of rectsfunctiondrawgoldRect(goldRectangle, ctx){
    ctx.drawImage(gold, goldRectangle.x, goldRectangle.y, goldRectangle.width, goldRectangle.height);
}
// draw finish linefunctiondrawFinishLine(){
    ctx.fillRect(finishX,0,5,ch);
}
body{ background-color: ivory; }
#canvas{border:1px solid red; }
<canvasid="canvas"width=500height=300></canvas>

Post a Comment for "Animating Images With Javascript"