Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

javascript - Can't make square on canvas move, and now the square won't draw either

I am trying to make an already drawn square move with the WASD keys.

I wasn't sure how to do this, so I looked up some code, and after about 2 hours came up with my own non-working code. It wasn't working, but at least it was drawing my square... Or was.

Now it isn't, and I have no clue why, here's my JavaScript:

    function initCanvas(){
    var ctx = document.getElementById('my_canvas').getContext('2d');
    ctx.addEventListener("keydown", move, true);

    function move(event){
            //W
            if(event.keyCode == 87){
                    y = y + 20;
            }
            //A
            else if(event.keyCode == 65){
                    x = x - 20;
            }

            //S
            else if(event.keyCode == 83){
                    y = y + 20;
            }

            //D
            else if(event.keyCode == 68){
                    x = x + 20;
            }  
    }

    var x = 0;
    var y = 0;

    ctx.fillStyle = "green";
    ctx.fillRect(x + 20, y + 20, 20, 20);

    }

 window.addEventListener('load', function(event){
    initCanvas();
 });

And HTML/CSS (entire page): http://pastebin.com/wjXv5tdK It probably has to do with the Event Listener because it seems to work without it.

TL;DR

So I basically want a square to be drawn on the canvas, and have the user control it using the WASD keys.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The reason the square doesn't draw anymore is you are trying to attach an event listener to a canvas context, and you can only attach listeners to the DOM object (the canvas). So if you change the statements to (for example):

    var canvas = document.getElementById('my_canvas');
    canvas.addEventListener("keydown", move, true);

And leave the ctx statements as they are the canvas will draw again. Unless you really need a canvas you might be better off using an svg img.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...