使用javascript动画图像 [英] Animating images with javascript

查看:97
本文介绍了使用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 how to implement the images with it.

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

旧代码:

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

I want to use this old code but i don't know what to remove and how to add the images that i have above for the cars. As you can see for this code i created squares instead of images.

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


推荐答案

以下是您重构的一些代码赛车图片:

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>

这篇关于使用javascript动画图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆