简体   繁体   中英

How can I reverse the direction of an element on a canvas?

I tried to make it so that when my 'Player' reaches a jumpDistance of 50, it falls down, so he makes a small ' jump ' .

The code might not be exactly "clean" at this point, but I'm getting started with Javascript.

I made the player jump by using a for loop with a delay. I tried to make him go down the same way, but this didn't work out the way I planned.

Fiddle demo

 <!DOCTYPE html> <html> <style> #canvas { background-color: rgba(177, 177, 177, 1); } </style> <body> <div> <p id="jumpDistance"></p> <p id="jumpDirection"></p> </div> <canvas id="canvas" width="800" height="400"></canvas> <script> var canvas = document.querySelector('#canvas'); var context = canvas.getContext('2d'); var xPos = 150; var yPos = 375; var jumpDistance = 0; function spelerObj() { canvas.width=canvas.width; context.rect(xPos, yPos, 25, 25); context.stroke(); context.fillStyle = "#FF0000"; context.fillRect(xPos, yPos, 25, 25); } function jump(e) { //Here the player jumps, with a loop that calculates it's jump-distance. //alert(e.keyCode); if (e.keyCode == 32) {// function upLoop() { setTimeout(function () { if(jumpDistance < 50) { yPos -= 1; jumpDistance++; upLoop(); spelerObj(); document.getElementById("jumpDistance").innerHTML = jumpDistance.toString(); } }, 1) } upLoop(); spelerObj(); } } document.onkeydown = jump; </script> </body> </html> 

You'd need a downloop that you can switch to at the top of the jump:

function upLoop() {
    setTimeout(function() {
        if (jumpDistance < 50) {
            yPos -= 1;
            jumpDistance++;
            upLoop();
        } else {
            downLoop();
        }

        spelerObj();
        document.getElementById("jumpDistance").innerHTML = jumpDistance.toString();
    }, 1)
}

function downLoop() {
    setTimeout(function() {
        if (jumpDistance > 0) {
            yPos += 1;
            jumpDistance--;
            downLoop();
        }

        spelerObj();
        document.getElementById("jumpDistance").innerHTML = jumpDistance.toString();
    }, 1)
}

Demo 1

You could also vary the timeout duration to add a pseudo-gravity effect.

Demo 2

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