简体   繁体   中英

Moving an image with arrow keys within a div with jS

I'm new to JS, so I apologize ahead of time if there's some simple answer! I've been going through threads and google for an hour so, and I haven't found anything :(

I'm trying to do a super mario-style sort of game where I move a character left and right. I've tried doing this incrementally (creating a square that moves based on arrow keys). A square's easy because you can get its x and y positions. However, I've switched to using an image, and I have no idea how to make it move left or right.

This is my html file:

<body>
    <div id = "char">
         <canvas id="myCanvas" width="400" height="400"></canvas>
         <script src="testing.js"></script>
    </div>
</body>

And this is what I'm trying to do in JS:

var img = new Image(),
    pic = document.getElementById("char"),
    switchVar=true;
pic.appendChild(img);
img.src = "2.png";
function move(e) {
    "use strict";
    var x = e.which || e.keycode; //gets the keycode that the user types

    switch(x) {
        case 39:
            //What do I do here??
            //the following doesn't work:
            //pic.style.left = parseInt(pic.style.left) + 100 + 'px';
            break;
    }
}
document.onkeydown = move;

I didn't include all the cases in switch, but my code would have cases for left, down, and up. Additionally, the reason why I'm appending the image in JS is because I'm trying to switch images when it runs left to right (switches from an img of a person extending their right leg to an img of a person extending their left leg)

Your image must have

position: absolute;

Because left, top, right and bottom only works on absolute positions.

pic.appendChild(img);
img.src = "2.png";
img.style.position = 'absolute';

And if you want image moves related to div #char the div must has position relative.

#char{position:relative;}

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