简体   繁体   中英

How to clear image right into next html canvas games?

I made a game, a race car game. The code is:

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

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

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

<!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 . Instead of carefully finding specific places to clear the canvas (ie ctx.clearRect(x + 150, -5, 260, 150); ), you should just up and do:

// 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 . 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:
// 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 . 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 . 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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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