2

I'm super new to coding and I've been trying to figure out animations with Javascript and HTML5. I have this "loading bar" like animation where a rectangle expands until it fills up the canvas. The idea is that once the canvas is covered the box clears and starts over. Instead, the rectangle fills the canvas and just starts flickering. Any ideas?

window.onload = function() {
  var wipeWidth = 0
  var canvas = document.getElementById('canvas');
  var context = canvas.getContext("2d");
  console.log(context);

  function drawRect() {
    context.clearRect(0,0,300,150)
    context.fillStyle = "#305ef2";
    context.rect(0, 0, wipeWidth, 150);
    context.fill()
    wipeWidth += 10
    if(wipeWidth > 300) {
      wipeWidth = 0;
    }
  }

  setInterval(drawRect,50)
}

2 Answers 2

1

You forgot to clear the path (beginPath). You can use fillRect instead to avoid this.

window.onload = function() {
  var wipeWidth = 0
  var canvas = document.getElementById('canvas');
  var context = canvas.getContext("2d");
  console.log(context);

  function drawRect() {
    context.clearRect(0, 0, 300, 150)
    context.fillStyle = "#305ef2";
    // this
    context.beginPath()
    context.rect(0, 0, wipeWidth, 150);
    context.fill()
    // or just this
    // context.fillRect(0, 0, wipeWidth, 150);
    wipeWidth += 10
    if (wipeWidth > 300) {
      wipeWidth = 0;
    }
  }

  setInterval(drawRect, 50)
}
<canvas id="canvas"></canvas>

Sign up to request clarification or add additional context in comments.

2 Comments

context.closePath() is not required in your code. It is not the adjunct of beginPath
@Blindman67 true, leaving explanation here stackoverflow.com/a/22857893/5089567
0

fillRect, requestAnimationFrame

var wipeWidth = 0
var canvas = document.getElementById('canvas');
var context = canvas.getContext("2d");
var direction = +10;

function drawRect() {
  context.clearRect(0, 0, canvas.width, canvas.height);
  context.fillStyle = "#305ef2";
  context.fillRect(0, 0, wipeWidth, 150);
  wipeWidth += direction
  if (wipeWidth > canvas.width || wipeWidth < 0) {
    direction *= -1;
  }
  requestAnimationFrame(drawRect)
}

drawRect()
canvas {
  background: gray;
}
<canvas id="canvas" width="600" height="50"></canvas>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.