Skip to content

Instantly share code, notes, and snippets.

@getify
Last active June 6, 2018 05:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save getify/d76413abc11d6d31e4a1f23d20761757 to your computer and use it in GitHub Desktop.
Save getify/d76413abc11d6d31e4a1f23d20761757 to your computer and use it in GitHub Desktop.
can't figure out the geometry... HELP!?

UPDATE

Solved: https://twitter.com/arcadio_g_s/status/1003147830163226624

Original

I'm having a geometry problem, and I need help!

For reference, here's the CodePen.

What I'm trying to do:

I want to call drawRect(..) with a canvas's context, and have it draw a rectangle as its coded to do.

I also want to be able to create another canvas which represents the 90-degree clockwise rotation of the first canvas. This second canvas actually has the reversed dimensions (width is height, height is width). I want to call the same drawRect(..) with that second canvas, and have it draw the rotated rectangle.

To be clear, I don't want to draw a different rectangle, I want to draw the same rectangle, but I want it to have been rotated in its drawing.

Requirements:

  • drawRect(..) cannot be modified
  • the values of rectWidth / rectHeight cannot be modified
  • the second canvas actually has to be of the reversed dimensions and the drawing has to have been drawn to it after the rotation
  • the rotation has to be programmatic through the canvas API, not through CSS/etc
  • Before calling drawRect(..), I need to be able to apply other transformations in addition to the rotation, such as flipping the drawing horizontally (via translate(..) and scale(-1,1)). In other words, after the rotation, the registration point needs to be back at 0,0 for subsequent transforms (if needed).
<!DOCTYPE html>
<html>
<head>
<title>Rotating An Rectangle</title>
</head>
<body>
<p>
<canvas id="canvas-1"></canvas>
</p>
<p>
<canvas id="canvas-2"></canvas>
</p>
<script>
var rectWidth = 375;
var rectHeight = 250;
function drawRect(ctx) {
ctx.beginPath();
ctx.rect(0,0,rectWidth,rectHeight);
ctx.stroke();
ctx.closePath();
}
window.onload = function onLoad(){
var cnv1 = document.getElementById("canvas-1");
var ctx1 = cnv1.getContext("2d");
var cnv2 = document.getElementById("canvas-2");
var ctx2 = cnv2.getContext("2d");
cnv1.width = rectWidth;
cnv1.height = rectHeight;
cnv2.width = rectHeight;
cnv2.height = rectWidth;
drawRect(ctx1);
// rotate 90 degrees clockwise
ctx2.save();
var cx = cnv2.width / 2;
var cy = cnv2.height / 2;
ctx2.translate(cx,cy);
ctx2.rotate(Math.PI / 2);
ctx2.translate(-cx,-cy);
drawRect(ctx2);
ctx2.restore();
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment