2
\$\begingroup\$

My animation is supposed to be used in my physics project I am making. I am using 10 millisecond setInterval() and setTimeout() and it glitches in and out. The setTimeout() handles the clear() function in my code, but I have the setTimeout() at 9 milliseconds and it works the best. If someone can help me, here's the code:

var canvas = document.getElementById("canvas")
var ctx = canvas.getContext("2d")
var x = 10
var y = 0
var xPos = 0
var yPos = 0
            
function updateVariables() {
    x = x * 0.9
    y = y * -0.9
    y = y + 1
    xPos += x
    yPos += y
}

function clear() {
    ctx.clearRect(0,0,600,600)
}
            
function Draw() {
    ctx.fillRect(xPos,yPos,20,10)
    ctx.fillRect(0,131,600,20)
    setTimeout(clear, 9)
}

function collisionCheck() {
    if (yPos > 120) {
        yPos = 120
    }
}

function keyCheck() {     
}

setInterval(Draw, 10)
setInterval(updateVariables, 1)
setInterval(collisionCheck, 10)
<canvas id="canvas"></canvas>

\$\endgroup\$
1
\$\begingroup\$

Your timeouts do not necessarily have to match up, i.e. a timeout of 10ms might not take exactly 10ms. You are also not considering the window's refresh rate at all. You might want to google "html5 canvas game loop" for ideas on how to restructure your game loop to function better and to help you expand upon your project, however, here's a basic example of your code restructured to remove the flickering:

var canvas = document.getElementById("canvas")
var ctx = canvas.getContext("2d")
var x = 10
var y = 0
var xPos = 0
var yPos = 0

function updateVariables() {
  x = x * 0.9
  y = y * -0.9
  y = y + 1
  xPos += x
  yPos += y
}

function clear() {
  ctx.clearRect(0,0,600,600)
}

function Draw() {
  collisionCheck();
  clear();
  ctx.fillRect(xPos,yPos,20,10)
  ctx.fillRect(0,131,600,20)
  window.requestAnimationFrame(Draw)
}

function collisionCheck() {
  if (yPos > 120) {
    yPos = 120
  }
}

function keyCheck() {}

window.requestAnimationFrame(Draw)
setInterval(updateVariables, 1)
<canvas id="canvas"></canvas>

The main difference here is the usage of window.requestAnimationFrame, which will get called everytime the window is redrawn.

\$\endgroup\$
  • 1
    \$\begingroup\$ Thanks! Never knew I'd get such a quick answer... 😆 \$\endgroup\$ – Aiden Huffman Nov 22 '18 at 13:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.