Lesson 6: Generalizing Rotation Angle

In the fifth lesson, we generalized our code in order to draw the curve stitch in any position, and to be able to easily set the length of the curve stitch's sides.

Now we are going to generalize the rotational angle at which the curve stitch is drawn. This is a slightly trickier thing to code for two reasons:

  1. The command to rotate requires you to enter the angle in units of 'radians' rather than degrees. If you don't know what a radian is, then don't worry. All you need to know is that it is easy to convert radians to degrees, and we have that conversion shown in the code.
  2. When we rotate something in a drawing, we need to ask what and where we are rotating it. Are we rotating "everything" in the drawing, or just one shape within it? And about what point in the canvas plane are we doing the rotation?

In answer to this second point, it turns out in our case that we only want to rotate our individual curve stitch, and we want to rotate it about the point where we draw its corner. To do that, we first need to "translate" (i.e. move) the center of the whole canvas coordinate systems (which is set by default to be at the top-left corner of the canvas HTML element) in such a way that the corner of our stitch will be at the corner of the canvas. Then we rotate the whole canvas by some amount, then we draw the curve stitch, then we go back to our original coordinate state.

If that sounds confusing -- DO NOT WORRY! It took me a fair bit of trial and error to get the rotations done right, and that is NORMAL in coding. The great thing is, once we've figured something out in coding, you can save that research in your code, start building upon it, and essentially forget all those pesky details!

This is how coding works: always start with something simple and then start improving upon it little by little.

Here's our stitch rotated by 45 degrees clockwise.