Created
June 28, 2012 15:38
-
-
Save ianoxley/3012067 to your computer and use it in GitHub Desktop.
Canvas transformations demo
This file contains hidden or 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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8" /> | |
<title>Canvas Transforms</title> | |
<style> | |
canvas { | |
border:1px solid #ccc; | |
} | |
</style> | |
</head> | |
<body> | |
<canvas id="theCanvas" width="400" height="400"></canvas> | |
<script> | |
var canvas = document.getElementById('theCanvas'), | |
context = canvas.getContext('2d'), | |
width = 50, | |
height = 50, | |
xPos = 100, | |
yPos = 100, | |
rotation = 45; | |
function deg2rad(degrees) { | |
return degrees * Math.PI / 180; | |
} | |
function draw() { | |
context.fillStyle = 'hsla(0, 50%, 50%, 0.7)'; | |
context.fillRect(xPos, yPos, width, height); | |
context.save(); | |
context.setTransform(1, 0, 0, 1, 0, 0); | |
var radians = deg2rad(rotation), | |
xMid = xPos + width / 2, | |
yMid = yPos + height / 2; | |
context.translate(xMid, yMid); | |
context.rotate(radians); | |
context.fillStyle = 'hsla(240, 50%, 50%, 0.7)'; | |
var xTrans = 0 - width / 2, | |
yTrans = 0 - height / 2; | |
context.fillRect(xTrans, yTrans, width, height); | |
context.restore(); | |
} | |
draw(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment