0

I see that in order to draw a rectangular path you can use a formula similar to the one found here.

I am wondering if there is something similar for a rectangular path?

EDIT: I'm looking to be able to have one point draw out the entire rectangular path in steps rather than to just have the entire rectangle appear.

i.e.

function redraw () {
  // 
     Code for the animation, while keeping track of last point 
    (such that the end animation is continuous)

  //
  clearScreen();
  ctx.beginPath();
  ctx.rect(x,y,5,5);
  ctx.stroke();
}

setInterval(redraw, 16);
redraw();

I'd prefer not using any external libraries as well

Somnium
  • 363
  • 1
  • 8
  • 17

1 Answers1

0

You could do use generator function to define the animation up front - forgive the poor code, it's just to give you the idea:

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");

// here we create a generator function,
// where we define each step:
function* rect(ctx, x, y, x2, y2) {  
  // top line
  for (let k = x; k <= x2; k++) {
    ctx.lineTo(k, y);
    yield;
  }

  // right line
  for (let j = y; j <= y2; j++) {
    ctx.lineTo(x2, j);
    yield;
  }

  // bottom line
  for (let k = x2; k >= x; k--) {
    ctx.lineTo(k, y2);
    yield;
  }

  // left line
  for (let j = y2; j >= y; j--) {
    ctx.lineTo(x, j);
    yield;
  }
}

const steps = rect(ctx, 10, 10, 80, 90);
ctx.strokeStyle = "black"

function draw () {
  if (!steps.next().done){
    ctx.stroke();
  } else {
    // here the animation is done
    ctx.fill();
  }

  // 60 fps
  requestAnimationFrame(draw); 
}

draw();
ZER0
  • 24,846
  • 5
  • 51
  • 54
  • what if you had to account for resizing as well? – Somnium Jan 20 '19 at 01:20
  • It really depends how the resizing *during* the animation would happen. – ZER0 Jan 20 '19 at 01:25
  • Best case scenario for me would be that if I resize, the next point on the path would conform to the new resized windows. With a circle, that wouldn't be too hard because I could keep a theta and have it applied to the parametric circle equation, but how would that work with a rectangle? – Somnium Jan 20 '19 at 04:53
  • My question is "how" the resize would happen during the animation, as said: for example, user interaction with dragging? Where is the origin? And what's happening to the animation when the resize happen? Will pause? Will continue? Will the resize animated as well *during* the other animation? So you would have several animations. There are too scenarios to take in account to give to you a generic answer. It really depends. What would happens to the lines already "finished"? – ZER0 Jan 20 '19 at 10:53