HTML5 Canvas - Translating circle into the middle

Results 1 to 2 of 2
  1. #1
    Registered yss is offline
    MemberRank
    Dec 2015 Join Date
    13Posts

    HTML5 Canvas - Translating circle into the middle

    Hello there,

    I have tried many things but I can't get this fixed.
    I want my circle moving on the x and y coordinated using my arrow keys. It doesn't need to be fancy. Only the system itself.

    It's like AgarIO, the circle is in the center of the screen while pressing the arrow keys.
    (Like this video: https://youtu.be/JXuxYMGe4KI?t=7m52s)

    Unfortunately the video is made in P5.js and it doesn't work in my attempts in pure javascript.

    My code (hastebin): https://hastebin.com/kisepetuho.js
    Raw code:

    Code:
    var canvas = document.getElementById('test');
    var context = canvas.getContext('2d');
    
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    
    var x = window.innerWidth/2;
    var y = window.innerHeight/2;
    
    var movement_speed = 6;
    var radius = 75;
    
    function draw() {
      context.clearRect(0, 0, canvas.width, canvas.height);
      
      context.fillStyle = 'black';
      context.font = "30px Arial";
      context.fillText("Current on: " + x + ", " + y, 15, 35);
      
      //context.translate(canvas.width/2-radius, canvas.height/2-radius);
      
      context.beginPath();
      context.arc(x,y,radius,0,2*Math.PI);
      context.stroke();  
      
      window.requestAnimationFrame(draw);
    }
    
    draw();  
    
    window.onkeydown = function (e) {
        var code = e.keyCode ? e.keyCode : e.which;
        if (code === 37) {
            x -= movement_speed;
        } else if (code === 38) { 
            y -= movement_speed;
        } else if (code === 39) {
            x += movement_speed;
        } else if (code === 40) {
            y += movement_speed;
        }
    };
    I hope someone can help me ^^

    - Pascal


  2. #2
    MMO Supervisor Biesmen is online now
    SupervisorRank
    Apr 2007 Join Date
    2,271Posts

    Re: HTML5 Canvas - Translating circle into the middle

    Start with triggering the draw function in your keydown event.

    Edit: https://www.kirupa.com/canvas/moving...s_keyboard.htm might help you out
    Forum Rules | Account Support | Subscribe
    RaGEZONE Facebook

    "The reason why people give up so fast is because they tend to look at how far they still have to go, instead of how far they have gotten."



Advertisement