Welcome!

Join our community of MMO enthusiasts and game developers! By registering, you'll gain access to discussions on the latest developments in MMO server files and collaborate with like-minded individuals. Join us today and unlock the potential of MMO server development!

Join Today!

HTML5 Canvas - Translating circle into the middle

yss

Initiate Mage
Joined
Dec 26, 2015
Messages
13
Reaction score
1
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: )

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

My code (hastebin):
Raw code:

Code:
[COLOR=#859900]var[/COLOR] canvas = [COLOR=#DC322F]document[/COLOR].getElementById([COLOR=#2AA198]'test'[/COLOR]);
[COLOR=#859900]var[/COLOR] context = canvas.getContext([COLOR=#2AA198]'2d'[/COLOR]);

canvas.width = [COLOR=#DC322F]window[/COLOR].innerWidth;
canvas.height = [COLOR=#DC322F]window[/COLOR].innerHeight;

[COLOR=#859900]var[/COLOR] x = [COLOR=#DC322F]window[/COLOR].innerWidth/[COLOR=#2AA198]2[/COLOR];
[COLOR=#859900]var[/COLOR] y = [COLOR=#DC322F]window[/COLOR].innerHeight/[COLOR=#2AA198]2[/COLOR];

[COLOR=#859900]var[/COLOR] movement_speed = [COLOR=#2AA198]6[/COLOR];
[COLOR=#859900]var[/COLOR] radius = [COLOR=#2AA198]75[/COLOR];

[COLOR=#859900]function[/COLOR] [COLOR=#268BD2]draw[/COLOR]() {
  context.clearRect([COLOR=#2AA198]0[/COLOR], [COLOR=#2AA198]0[/COLOR], canvas.width, canvas.height);
  
  context.fillStyle = [COLOR=#2AA198]'black'[/COLOR];
  context.font = [COLOR=#2AA198]"30px Arial"[/COLOR];
  context.fillText([COLOR=#2AA198]"Current on: "[/COLOR] + x + [COLOR=#2AA198]", "[/COLOR] + y, [COLOR=#2AA198]15[/COLOR], [COLOR=#2AA198]35[/COLOR]);
  
  [COLOR=#586E75]//context.translate(canvas.width/2-radius, canvas.height/2-radius);[/COLOR]
  
  context.beginPath();
  context.arc(x,y,radius,[COLOR=#2AA198]0[/COLOR],[COLOR=#2AA198]2[/COLOR]*[COLOR=#DC322F]Math[/COLOR].PI);
  context.stroke();  
  
  [COLOR=#DC322F]window[/COLOR].requestAnimationFrame(draw);
}

draw();  

[COLOR=#DC322F]window[/COLOR].onkeydown = [COLOR=#859900]function[/COLOR] (e) {
    [COLOR=#859900]var[/COLOR] code = e.keyCode ? e.keyCode : e.which;
    [COLOR=#859900]if[/COLOR] (code === [COLOR=#2AA198]37[/COLOR]) {
        x -= movement_speed;
    } [COLOR=#859900]else[/COLOR] [COLOR=#859900]if[/COLOR] (code === [COLOR=#2AA198]38[/COLOR]) { 
        y -= movement_speed;
    } [COLOR=#859900]else[/COLOR] [COLOR=#859900]if[/COLOR] (code === [COLOR=#2AA198]39[/COLOR]) {
        x += movement_speed;
    } [COLOR=#859900]else[/COLOR] [COLOR=#859900]if[/COLOR] (code === [COLOR=#2AA198]40[/COLOR]) {
        y += movement_speed;
    }
};

I hope someone can help me ^^

- Pascal
 
Back
Top