Created
March 20, 2012 00:27
-
-
Save jonathantneal/2128995 to your computer and use it in GitHub Desktop.
Canvas Prototype: Rotation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function boundingWidthFromAngle ( degree , width , height ) { | |
with ( Math ) { | |
degree = degree % 360; | |
var radian = degree * PI / 180; | |
height = ( ( degree >= 0 && degree < 90 ) || ( degree >= 180 && degree < 270 ) ) ? height : -height; | |
return ceil( abs( height * sin( radian ) + width * cos( radian ) ) ); | |
} | |
} | |
HTMLCanvasElement.prototype.rotation = function (value) { | |
value = parseFloat(value) || 0; | |
var | |
canvas = this, | |
canvasClone = document.createElement('canvas'), | |
context = canvas.getContext('2d'), | |
width = context.canvas.width, | |
height = context.canvas.height, | |
radian = Math.PI * value / 180; | |
newWidth = boundingWidthFromAngle(value, width, height); | |
newHeight = boundingWidthFromAngle(value, height, width); | |
// console.log(newWidth, newHeight); | |
// Math.toRadian = function (degree) { return degree * Math.PI / 180; } | |
// When the rotation is between (0 and 90) or degrees... | |
// Say (a,b) is your top-right corner, and theta is your angle. If theta is between 0 and pi/2, asin(theta)+bcos(theta) will be your highest point. At pi/2, switch to asin(theta)-bcos(theta), at pi, switch to -asin(theta)-bcos(theta) and a 3pi/2 to -asin(theta)+bcos(theta). Round up to the nearest pixel. | |
// Math.ceil(Math.abs(width * Math.sin(radian) + height * Math.cos(radian))); | |
// Math.ceil(Math.abs(width * Math.sin() + height * Math.cos(degree * Math.PI / 180))); | |
// Math.ceil(Math.abs(-width * Math.sin(degree * Math.PI / 180) + height * Math.cos(degree * Math.PI / 180))); | |
canvasClone.width = width; | |
canvasClone.height = height; | |
canvasClone.getContext('2d').putImageData(context.getImageData(0, 0, width, height), 0, 0); | |
canvas.width = width; | |
canvas.height = height; | |
console.log(width, newWidth); | |
// square root of | |
// context.translate(width / 2, height / 2); | |
context.rotate(radian); | |
// context.translate(0, 0); | |
context.drawImage(canvasClone, 0, 0); | |
return canvas; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment