使用javascript

时间:2016-05-15 19:12:05

标签: javascript html5 canvas

我试图让图像互相竞争,一旦其中一个图像通过终点线就会显示胜利者。

我有一些用于动画的旧代码,但我不知道如何用它来实现图像。

<html>
<head>
    <title>Canvas Race</title>
    <script src="jquery-2.2.3.js"></script>
     <style type="text/css">
        canvas {
            border: 1px solid black;
            background-image: url("http://www.gamefromscratch.com/image.axd?picture=road2048v2.png");
            background-size: 200px 300px;
            background-position-y: -81px;
        }
        </style>
</head>
<body>

    <canvas id="canvas" width="1100" height="150" >
    <script>
        var blueCar = new Image();
        var redCar = new Image();

        // images
        function image(){
            blueCar.src = "http://worldartsme.com/images/car-top-view     clipart-1.jpg";
            redCar.src = "http://images.clipartpanda.com/car-clipart-top-view-free-vector-red-racing-car-top-view_099252_Red_racing_car_top_view.png";

        }
        window.onload = function draw(){
            var ctx = document.getElementById('canvas').getContext('2d');
            ctx.globalCompositeOperation = 'destination-over';
            window.requestAnimationFrame(draw);
            window.requestAnimationFrame(animate);

            // finish line
            ctx.beginPath();
            ctx.moveTo(1020, 150);
            ctx.lineTo(1020, 0);
            ctx.strokeStyle = "#FFEF0E";
            ctx.stroke();

            //blue car
            ctx.save();
            if(blueCar.complete){

                ctx.drawImage(blueCar, 10, 10, 100, 60);
            }
            // red car
            if(redCar.complete){
                ctx.drawImage(redCar, 10, 80, 100, 60);
            }

        }

        image();

    </script>
    </canvas>
    <div id="winner"></div>

</body>
</html>

旧代码:

我想使用这个旧代码,但我不知道要删除什么以及如何添加上面的汽车图像。正如您在此代码中看到的,我创建了正方形而不是图像。

window.requestAnimFrame = (function(callback) {
         return window.requestAnimationFrame ||     window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
         function(callback) {
         window.setTimeout(callback, 1000 / 60);
         };
         })();

         // drawing red square
         function drawRedRect(redCar, ctx) {
         ctx.beginPath();
         ctx.drawImage(redCar, 5, 5);
         }

         // finish line
         function drawFinishLine(ctx){
         ctx.beginPath();
         ctx.moveTo(1040, 150);
         ctx.lineTo(1040, 0);
         ctx.stroke();
         }
         // this is drawing the blue square
         function drawBlueRect(blueRectangle, ctx){
         ctx.beginPath();
         ctx.rect(blueRectangle.x, blueRectangle.y, blueRectangle.width, blueRectangle.height);
         ctx.fillStyle = 'blue';
         ctx.fill();
         }

         // red square animation
               function animate(lastTime, redCar, blueRectangle, runAnimation, canvas, ctx) {
                 if(runAnimation.value) {
                  // update
                   var time = (new Date()).getTime();
                   var timeDiff = time - lastTime;

                  // pixels / second
                   var redSpeed = Math.floor((Math.random() * 400) + 1);
                  var blueSpeed = Math.floor((Math.random() * 400) + 1);
                   var linearDistEachFrameRed = redSpeed * timeDiff / 1000;
                  var linearDistEachFrameBlue = blueSpeed * timeDiff / 1000;
                   var currentX = redRectangle.x;
                  var currentZ = blueRectangle.x;

                   if(currentX < canvas.width - redRectangle.width - redRectangle.borderWidth / 2) {
                     var newX = currentX + linearDistEachFrameRed;
                     redRectangle.x = newX;
                   }
                  if(currentZ < canvas.width - blueRectangle.width - blueRectangle.borderWidth / 2) {
                     var newZ = currentZ + linearDistEachFrameBlue;
                     blueRectangle.x = newZ;
                   }

                    console.log(redSpeed);
                    console.log(blueSpeed);
                   // clear
                   ctx.clearRect(0, 0, canvas.width, canvas.height);

                   // draw
                  drawFinishLine(ctx);
                   drawRedRect(redRectangle, ctx);
                  drawBlueRect(blueRectangle, ctx);
                  //winner(win);

                   // request new frame
                   requestAnimFrame(function() {
                     animate(time, redRectangle, blueRectangle, runAnimation, canvas, ctx);
                   });
                 }
               }

         var canvas = document.getElementById('myCanvas');
         var ctx = canvas.getContext('2d');
         var win = document.getElementById('Winner')

         //blue square
         var blueRectangle = {
         x: 5, y: 30, width: 45, height: 25, borderWidth:5
         };

         //red square
         var redRectangle = {
         x: 5,
         y: 90,
         width: 45,
         height: 25,
         borderWidth: 5
         };

         /!*
         * define the runAnimation boolean as an obect
         * so that it can be modified by reference
         *!/
         var runAnimation = {
         value: false
         };

         // add click listener to canvas
         document.getElementById('myCanvas').addEventListener('click', function() {
         // flip flag
         runAnimation.value = !runAnimation.value;

         if(runAnimation.value) {
         var date = new Date();
         var time = date.getTime();
         animate(time, redRectangle, blueRectangle, runAnimation, canvas, ctx);
         }
         });

         drawFinishLine(ctx);
         drawRedRect(redRectangle, ctx);
         drawBlueRect(blueRectangle, ctx);
        //winner(win);

1 个答案:

答案 0 :(得分:0)

以下是您为赛车图片重构的部分代码:

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

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

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

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

function animate(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 over
    if(hasRedWon){ alert('Red wins'); return; }
    if(hasGoldWon){ alert('Gold wins'); return; }

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

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