如何在画布中移动图像?

时间:2016-05-16 16:27:36

标签: javascript html5-canvas

我正在努力让图片移动,但我不断收到错误value说它没有定义。我不确定我是否正在做这个正确的,有人只是让这个东西工作,请!!

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

    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 canvas = document.getElementById('canvas');
        var ctx = canvas.getContext('2d');
        ctx.globalCompositeOperation = 'destination-over';
        window.requestAnimationFrame(draw);

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

    //animate on click
    document.getElementById('canvas').addEventListener('click', function animate(lastTime, redCar, blueCar, runAnimation, canvas, ctx) {
        if (runAnimation.value) {
            // update
            var time = (new Date()).getTime();
            var timeDiff = time - lastTime;

            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 = redCar.x;
            var currentZ = blueCar.x;

            if (currentX < canvas.width - redCar.width - redCar.borderWidth / 2) {
                var newX = currentX + linearDistEachFrameRed;
                redCar.x = newX;
            }

            if (currentZ < canvas.width - blueCar.width - blueCar.borderWidth / 2) {
                var newZ = currentZ + linearDistEachFrameBlue;
                blueCar.x = newZ;
            }

            //clear
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            image();

            requestAnimFrame(function() {
                animate(time, redCar, blueCar, runAnimation, canvas, ctx);
            });
        }

        var runAnimation = {
            value: false
        };
    });
    image();

1 个答案:

答案 0 :(得分:2)

我想把它扔给你作为如何在画布上制作汽车动画的例子。我从上面的例子中取出了蓝色的汽车,只需将其移动成椭圆形,没有任何旋转。您可以通过ctx.translate()ctx.rotate()方法轻松实现汽车的旋转。

您可以看到我首先加载图像资源,只在资源加载时启动我的动画。然后,调用循环,调用绘制和更新,向它们传递刻度和差异,以允许在这些方法内进行平滑的移动计算。

<!DOCTYPE html>
<html>
    <head>
        <title>Image Animation Test</title>
        <meta charset="UTF-8">
        <script>
            const BLUE_URL = "http://worldartsme.com/images/car-top-view-clipart-1.jpg";
            const DESIRED_ROTATION_SPEED = Math.PI / 2;

            var raf;
            var blueCar;
            var ctx;
            var lastTick = 0;
            var position = { x:0, y:0, angle:0 };
            var center = { x:0, y:0 };

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

            function clearContext(fillColor) {
                ctx.fillStyle = fillColor;
                ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
            }

            function update(gameTime) {
                position.angle += (gameTime.diff / 1000) * DESIRED_ROTATION_SPEED;
                if (position.angle > (Math.PI * 2)) {
                    position.angle -= Math.PI * 2;
                }

                position.x = center.x + (Math.cos(position.angle) * 180);
                position.y = center.y + (Math.sin(position.angle) * 140);
            }

            function draw(gameTime) {
                clearContext('#101010');
                var drawHeight = 100;
                var drawWidth = drawHeight * blueCar.width / blueCar.height;
                ctx.drawImage(blueCar, 0, 0, blueCar.width, blueCar.height, position.x - (drawWidth / 2), position.y - (drawHeight / 2), drawWidth, drawHeight);
            }

            function loop(tick) {
                var diff = tick - lastTick;
                lastTick = tick;
                var gameTime = { tick:tick, lastTick:lastTick, diff:diff };
                update(gameTime);
                draw(gameTime);
                raf(loop);
            }

            function init(event) {
                console.log(BLUE_URL);
                var canvas = document.getElementById('canvas');
                canvas.width = 800;
                canvas.height = 600;
                center.x = canvas.width / 2;
                center.y = canvas.height / 2;
                position.x = center.x;
                position.y = center.y;
                ctx = canvas.getContext('2d');
                raf = getRaf();
                blueCar = new Image();
                blueCar.addEventListener('load', function(event) {
                    startAnimation();
                }, false);
                blueCar.src = BLUE_URL;
            }

            function startAnimation() {
                raf(loop);
            }

            window.addEventListener('load', init, false);
        </script>
    </head>
    <body>
        <canvas id="canvas"><h1>Canvas not supported</h1></canvas>
    </body>
</html>