Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9086717
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T21:33:24+00:00 2026-06-16T21:33:24+00:00

I’m very new to programming and I’m trying to create some code that will

  • 0

I’m very new to programming and I’m trying to create some code that will allow me to move a square around the Canvas by pressing arrow keys. I’m able to get the square to move, but its motion isn’t very smooth. I have it moving by increments of 10 pixels at a time, so I understand why it feels kind of jerky, because there isn’t any animation between each position of 10-frames-difference, but having it move by smaller increments makes it far too slow. What I’ve done so far is below:

window.onload = function init() {
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    setInterval(gameLoop,50);
    window.addEventListener('keydown',whatKey,true);
}

avatarX = 400
avatarY = 300

function gameLoop() {
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    canvas.width = 800
    canvas.height = 600
    ctx.fillRect(avatarX,avatarY,50,50);
}

function whatKey(e) {
    switch(e.keyCode) {
    case 37:
        avatarX = avatarX - 10;
        break;
    case 39:
        avatarX = avatarX + 10;
        break;
    case 40:
        avatarY = avatarY + 10;
        break;
    case 38:
        avatarY = avatarY - 10;
        break;
    }
}

Every time I press the arrow key right, I would like for the square to move smoothly in that direction at a constant rate. Thanks in advance for any help at all!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T21:33:25+00:00Added an answer on June 16, 2026 at 9:33 pm

    Added a few things, the first is requestAnimationFrame for reasons explained here.

    I then added a keyup and keydown event handler, these will keep track of what keys are currently being pushed by using an array. If the key is true in the array its currently being pushed, if false it isn’t. This method also allows you to press and hold multiple keys at once.

    I then added velocity variables which increase or decreased based on whats being pressed, and a maxSpeed variable so you don’t go faster than a certain speed. The maxSpeed variable could be removed and the incrementing and decrementing velX and velY could also be removed, you would just need to uncomment the lines I left. It just seemed to go too fast at 10 thats why I added the gradual speed up.

    Live Demo

    The above will seem jerky, because the frame is scrolling with the up and down arrows since the canvas is a bit bitter, use the full screen link to fully test the movement.

    Full Screen link

    (function () {
      var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
      window.requestAnimationFrame = requestAnimationFrame;
    })();
    
    
    window.onload = function init() {
      var canvas = document.getElementById("canvas");
      var ctx = canvas.getContext("2d");
      gameLoop();
    }
    
    window.addEventListener("keydown", function (e) {
      keys[e.keyCode] = true;
    });
    window.addEventListener("keyup", function (e) {
      keys[e.keyCode] = false;
    });
    
    
    var avatarX = 400,
      avatarY = 300,
      velX = 0,
      velY = 0,
      keys = [],
      maxSpeed = 10;
    
    function gameLoop() {
      whatKey();
      var canvas = document.getElementById("canvas");
      var ctx = canvas.getContext("2d");
      canvas.width = 800;
      canvas.height = 600;
    
      avatarX += velX;
      avatarY += velY;
    
      ctx.fillRect(avatarX, avatarY, 50, 50);
      requestAnimationFrame(gameLoop);
    }
    
    function whatKey() {
      if (keys[37]) {
        //velX = -10;
        if (velX > -maxSpeed) {
          velX -= 0.5;
        }
      }
    
      if (keys[39]) {
        //velX = 10;
        if (velX < maxSpeed) {
          velX += 0.5;
        }
      }
      if (keys[40]) {
        //velY = 10;
        if (velY < maxSpeed) {
          velY += 0.5;
        }
      }
      if (keys[38]) {
        //velY = -10;
        if (velY > -maxSpeed) {
          velY -= 0.5;
        }
      }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to create an if statement in PHP that prevents a single post
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
I need a function that will clean a strings' special characters. I do NOT
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text
Configuring TinyMCE to allow for tags, based on a customer requirement. My config is
I am trying to understand how to use SyndicationItem to display feed which is

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.