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

前端 未结 2 560
悲&欢浪女
悲&欢浪女 2020-12-20 10:32

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

2条回答
  •  失恋的感觉
    2020-12-20 11:04

    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.

提交回复
热议问题