简体   繁体   English

如何清除图像进入下一个HTML画布游戏?

[英]How to clear image right into next html canvas games?

I made a game, a race car game. 我做了一个游戏,一个赛车游戏。 The code is: 代码是:

index.html index.html

<!DOCTYPE html>
<html>
<head>
    <title> Race car </title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script>
        var ctx;

            //save the parameters to variables for easier clearing
        var x_Car = 30,
            y_Car = 95,
            width_Car = 110,
            height_Car = 55,
            imgCar = new Image();
        imgCar.src = "cars/race-car.png";

        var nrMonsters = 0,
            imgMonster = new Image();
        imgMonster.src = "Monster/yellow_monster.png";

        var width_Monster = 100;
        var height_Monster = 20;
        var x_Monster = 50;
        var y_Monster = 5;
        var speed = 1;

        // function drawMonster() {
        //     ctx.drawImage(imgMonster, x_Monster, y_Monster, width_Monster, height_Monster);
        // }
        function drawCar() {
            ctx.drawImage(imgCar, x_Car, y_Car, width_Car, height_Car);
        }

        function rand() {
            var left = 50;
            var right = 150;
            var z;
            var random = Math.random();

            if (random > 0.5) {
                 z = right;
            } else {
                 z = left;
            }
            return z;
        }

        valX = rand();

        function draw(x, y) {
           //ctx.save();
            if (valX == 50 && x_Car > 75) {
                ctx.clearRect(x + 5, -5, 150, 150);  // 95 cu 150
            } else if (valX == 50) {
                ctx.clearRect(x + 5, y, 150, 10);
            } else if (valX == 150 && x_Car < 32){
                ctx.clearRect(x + 150, -5, 260, 150);  // 95 cu 150
            } else if (valX == 150) {
                ctx.clearRect(x + 150, y, 260, 10);
            }

            ctx.drawImage(imgMonster, valX, y, width_Monster, height_Monster);
            ctx.restore();

            y += speed;
            if (y == y_Car && x_Car < 32 && valX == 50
             || y == y_Car && x_Car > 75 && valX == 150
             || y > y_Car && y < y_Car + height_Car && x_Car < 32 && valX == 50
             || y > y_Car && y < y_Car + height_Car && x_Car > 75 && valX == 150) {
                window.location.href = "you_lost_the_game.html";
                // alert("You lost the game");
            }

            var loopTimer = setTimeout("draw(" + x + ", " + y + ")", 20);

           if (y == 150 && nrMonsters < 15
            || y == 160 && nrMonsters >= 15) {
                valX = rand();
                nrMonsters++;

                console.log(nrMonsters);
                document.getElementById("numarObstacole").innerHTML  = nrMonsters;

                if (nrMonsters == 5
                 || nrMonsters == 10
                 || nrMonsters == 20
                 || nrMonsters == 25) {
                // || nrMonsters == 20 || nrMonsters == 27) {
                    speed += 1;
                } else if (nrMonsters == 15) {
                    speed += 1;
                }

                draw(0, 0);

                if (nrMonsters == 25) {
                    window.location.href = "win.html";
                }
           }

        }

        function init() {
            ctx = document.getElementById("canvas").getContext("2d");
            // audio
            // myAudio = new Audio('http://static1.grsites.com/archive/sounds/cars/cars002.wav'); 
            myAudio = new Audio("Sounds/Get low NFS.mp3");
            myAudio.addEventListener("ended", function() {
                this.currentTime = 0;
                this.play();
            }, false);
            myAudio.play(); 

            //draw wall

            draw(0, 0); 
            drawCar();

            function moveRight() {
                ctx.clearRect(x_Car, y_Car, width_Car, height_Car);
                x_Car = x_Car + 120;
                if(x_Car > 220){
                    x_Car -= 120;
                    drawCar();
                } else {
                    drawCar();
                }
            }

            function moveLeft() {
                ctx.clearRect(x_Car, y_Car, width_Car, height_Car);
                x_Car = x_Car-120;
                if (x_Car < 20) {
                    x_Car += 120;
                    drawCar();
                } else {
                    drawCar();
                }
            }

            function moveUp() {
                ctx.clearRect(x_Car, y_Car, width_Car, height_Car);
                y_Car = y_Car-20;
                drawCar();
            }

            function moveDown() {
                ctx.clearRect(x_Car, y_Car, width_Car, height_Car);
                y_Car = y_Car + 20;
                drawCar();
            }

            window.addEventListener("keypress", checkKeyPressed, false);

            function checkKeyPressed(e) {
                if (e.charCode == "97" || e.charCode == 027) {
                    moveLeft();
                }
                if (e.charCode == "100" || e.charCode== 026) {
                    moveRight();
                }
                if (e.charCode == "119" || e.charCode== 024) {
                    moveUp();
                }
                if (e.charCode == "115" || e.charCode== 025) {
                    moveDown();
                }
            }
        }

        function moveRight() {
            ctx.clearRect(x_Car, y_Car, width_Car, height_Car);
            x_Car = x_Car + 120;
            if (x_Car > 220) {
                x_Car -= 120;
                drawCar();
            } else {
                drawCar();
            }
        }

        function moveLeft() {
            ctx.clearRect(x_Car, y_Car, width_Car, height_Car);
            x_Car = x_Car - 120;
            if(x_Car < 20) {
                x_Car += 120;
                drawCar();
            } else {
                drawCar();
            }
        }

        function moveUp() {
            ctx.clearRect(x_Car, y_Car, width_Car, height_Car);
            y_Car = y_Car - 20;
            drawCar();
        }

        function moveDown() {
            ctx.clearRect(x_Car, y_Car, width_Car, height_Car);
            y_Car = y_Car + 20;
            drawCar();
        }

        window.addEventListener("keypress", checkKeyPressed, false);

        function checkKeyPressed(e) {
            if (e.charCode == "97") {
                moveLeft();
            }
            if (e.charCode == "100") {
                moveRight();
            }
            if (e.charCode == "119") {
                moveUp();
            }
            if (e.charCode == "115") {
                moveDown();
            }
        }
    </script>
</head>
<body onLoad="init();">
    <div id="moveButons">
        <table>
            <tr>
                <td></td>
                <td>
                    <input class="button" id="up" type="button" value="Move Up" onclick="moveUp()"/>
                </td>
                <td></td>
            </tr>
            <tr>
                <td>
                    <input class="button" id="left" type="button" value="Move Left" onclick="moveLeft()"/>
                </td>
                <td></td>
                <td>
                    <input class="button" id="right" type="button" value="Move Right" onclick="moveRight()"/>
                </td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <input class="button" id="down" type="button" value="Move Down" onclick="moveDown()"/>
                </td>
                <td></td>
            </tr>
        </table>
    </div>
    <p class="numarObstacole">
        Ai trecut peste <span id="numarObstacole"> 0 </span> obstacole
    </p>
    <canvas id="canvas">
        Your browser doesn't support the HTML5 element canvas.
    </canvas>
</body>
</html>

style.css style.css

* {
    margin: 0;
    padding: 0;
}

body {
    background-color: yellow;
}

#canvas {
    background: white;
    margin-left: 50%;
    position: absolute;
    left: -206px;
    width: 412px;
    height: 100%;
    background-image: url("street/street (2).jpg");
    background-position: 0px 0px;
    background-repeat: repeat-y;

    -webkit-animation: animatedBackground 5s linear infinite;
       -moz-animation: animatedBackground 5s linear infinite;
            animation: animatedBackground 5s linear infinite;
}

#moveButons {
    position: absolute;
    left: 20px;
    top: 50px;
}

@-webkit-keyframes animatedBackground {
    from {  background-position: 0 100%;  }
      to {  background-position: 0 0;     }
}
@-moz-keyframes animatedBackground {
    from {  background-position: 0 100%;  }
      to {  background-position: 0 0;     }
}
@keyframes animatedBackground {
    from {  background-position: 0 100%;  }
      to {  background-position: 0 0;     }
}

#lostGame {
    text-align: center;
    color: red;
    margin-top: 175px;
}

#win {
    text-align: center;
    color: blue;
    margin-top: 175px;
}

#canvas_lost {
    width: 320px;
    height: 240px;
    background: url("Joker/the-joker-laughing-1.jpg");
    margin-left: 50%;
    position: absolute;
    left: -160px;
}

#canvas_win {
    width: 320px;
    height: 240px;
    background: url("Joker/joker.gif");
    margin-left: 50%;
    position: absolute;
    left: -160px;
}

.button {
    color: blue;
    font-size: 17px;
    text-align: center;
    background: #6BA7FA;
    width: 100px;
}

.numarObstacole {
    position: absolute;
    color: #1F1;
    background: silver;
    font-size: 20px;
    font-family: Serif;
}

#numarObstacole {
    color: blue;
    font-size: 22px;
    font-family: sans-serif;
}

win.html win.html

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="style.css">
    <title> Win </title>
    <script>
        function init() {
            var canvas = document.getElementById("canvas_win");
            var ctx = canvas.getContext("2d");

            var myAudio = new Audio("Sounds/Fireworks Finale.mp3"); 
            myAudio.addEventListener("ended", function() {
                this.currentTime = 0;
                this.play();
            }, false);
            myAudio.play();

            var otherAudio = new Audio("Sounds/Audience_Applause.mp3"); 
            otherAudio.addEventListener("ended", function() {
                this.currentTime = 0;
                this.play();
            }, false);
            otherAudio.play()
        }
    </script>
</head>
<body onLoad="init();">
    <h1 id="win"> You win </h1>
    <canvas id="canvas_win">
        Your browser doesn't support the HTML5 element canvas.
    </canvas>
</body>
</html>

you_lost_the_game.html you_lost_the_game.html

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="style.css">
    <title> You lost the game </title>
    <script>
        function init() {
            var canvas = document.getElementById("canvas_lost");
            var ctx = canvas.getContext("2d");

            var myAudio = new Audio("Sounds/hahaha-Peter_De_Lang.mp3");
            myAudio.addEventListener("ended", function() {
                this.currentTime = 0;
                this.play();
            }, false);
            myAudio.play();
        }
    </script>
</head>
<body onLoad="init();">
    <h1 id="lostGame"> You lost the game </h1>
    <canvas id="canvas_lost">
        Your browser doesn't support the HTML5 element canvas.
    </canvas>
</body>
</html>

The problem is with the monster image. 问题出在怪物形象上。

When this image comes to the car image with a bigger speed, it leaves behind some "trail". 当此图像以更高的速度出现在汽车图像上时,它会留下一些“痕迹”。

How can I solve it? 我该如何解决?

The answer 答案

I believe your issue is with your clearing with clearRect . 我相信您的问题在于您使用clearRect清除。 Instead of carefully finding specific places to clear the canvas (ie ctx.clearRect(x + 150, -5, 260, 150); ), you should just up and do: 与其仔细寻找清理画布的特定位置(即ctx.clearRect(x + 150, -5, 260, 150); ), ctx.clearRect(x + 150, -5, 260, 150);直接进行以下操作:

// Get <canvas> on a variable
var canvas = document.getElementById("canvas");

// ctx is still the same
var ctx = canvas.getContext("2d");


function draw(x, y) {

    // Clears everything on the canvas on every loop
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    ...

That way, any "trail" left by the car or by the monster will be cleared on every frame. 这样,汽车或怪物留下的任何“痕迹”都将在每一帧清除。


Now, for coding suggestions: 现在,对于编码建议:

  1. Instead of adding an event listener for when an audio ends, simply turn the loop property to true . 无需在音频结束时添加事件侦听器,只需将loop属性设置为true Here's some code: 这是一些代码:
// Your current code
var myAudio = new Audio("Sounds/---.mp3"); 
myAudio.addEventListener("ended", function() {
    this.currentTime = 0;
    this.play();
}, false);
myAudio.play();


// Some smaller and more efficient code
var myAudio = new Audio("Sounds/---.mp3");
myAudio.loop = true;  // Restarts the audio every time it reaches the end
myAudio.play();

  1. This code doesn't make much sense: 这段代码没有多大意义:
if (nrMonsters == 5
 || nrMonsters == 10
 || nrMonsters == 20
 || nrMonsters == 25) {
// || nrMonsters == 20 || nrMonsters == 27) {
    speed += 1;
} else if (nrMonsters == 15) {
    speed += 1;
}

If something do this otherwise do the same thing ? 如果事情 这样做,否则做同样的事情 Here's a quick fix: 快速解决方法:

if (nrMonsters == 5
 || nrMonsters == 10
 || nrMonsters == 15
 || nrMonsters == 20
 || nrMonsters == 25) {
    speed += 1;
}

  1. You don't need this else here: 您在这里不需要else
// From the moveRight() function
if (x_Car > 220) {
    x_Car -= 120;
    drawCar();
} else {
    drawCar();
}

You see, if you're going to drawCar() anyway, you don't need to put it inside the if . 您会发现,无论如何,如果要使用drawCar() ,则无需将其放入if Here's better code: 这里是更好的代码:

if (x_Car > 220) {
    x_Car -= 120;
}
drawCar();

  1. You shouldn't have those leading zeroes: 您不应该使用这些前导零:
// From the checkKeyPressed() function
if (e.charCode == "97" || e.charCode == 027) {  ...  }

That 027 (and some subsequent numbers with leading a 0 ) gets treated as a base 8 number . 那个027 (和一些后面带有0数字)被当作基数8 I'm pretty sure it wasn't your intention to have an octal number there, but if that's the case, then the proper formatting is prepeding it with 0o instead of simply a zero. 我很确定这不是您想要在其中使用八进制数的意图,但是如果是这样,那么正确的格式是在其前面加上0o而不是一个零。

var binal = 0b10;  // (0b)10 in base 2 is equal to 2 in decimal
var octal = 0o10;  // (0o)10 in base 8 is equal to 8 in decimal
var hexal = 0x10;  // (0x)10 in base 16 is equal to 16 in decimal

That's all that I found. 这就是我发现的全部。 I wish you good luck with your game! 祝您游戏顺利! Cheers! 干杯!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM