Skip to content

Instantly share code, notes, and snippets.

@redgeoff
Created November 23, 2016 22:44
Show Gist options
  • Save redgeoff/f9d84027119ce716d598da489d320a13 to your computer and use it in GitHub Desktop.
Save redgeoff/f9d84027119ce716d598da489d320a13 to your computer and use it in GitHub Desktop.
Rotated Squares
<canvas style="position:absolute;left:100px;top:100px;" id="canvas1"></canvas>
<canvas style="position:absolute;left:242px;top:100px;" id="canvas2"></canvas>
<canvas style="position:absolute;left:171px;top:171px;" id="canvas3"></canvas>
<canvas style="position:absolute;left:171px;top:29px;" id="canvas4"></canvas>
<script>
// An example that demonstrates how rotated squares can be drawn without rounding
// errors. This method uses a canvas for each rectangle and rotates the entire
// canvas. Our initial approach was to calculate the vertices, rotate them around
// the center of the square and then draw the square represented by the rotated
// vertices. This leads to misalignment though as there are rounding errors when
// rounding to the nearest pixel.
var drawRotatedRect = function (canvas) {
var x = 21;
var y = 21;
var width = 100;
var height = 100;
var canvasWidth = Math.ceil(Math.sqrt(width*width + height*height));
var canvasHeight = canvasWidth;
canvas.width = canvasWidth;
canvas.height = canvasWidth;
var ctx = canvas.getContext('2d');
ctx.translate( x+width/2, y+height/2 );
ctx.rotate(45*Math.PI/180);
ctx.rect( -width/2, -height/2, width,height);
ctx.stroke();
};
drawRotatedRect(document.getElementById('canvas1'));
drawRotatedRect(document.getElementById('canvas2'));
drawRotatedRect(document.getElementById('canvas3'));
drawRotatedRect(document.getElementById('canvas4'));
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment