Skip to content

Instantly share code, notes, and snippets.

@jmjpro
Last active December 18, 2015 10:59
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 jmjpro/5772557 to your computer and use it in GitHub Desktop.
Save jmjpro/5772557 to your computer and use it in GitHub Desktop.
rotate an image on an HTML5 canvas
<html>
<head>
<style>
img {
display:none;
}
</style>
<script src="canvasUtil.js"></script>
</head>
<body>
<img id="dp" src="http://octodex.github.com/images/daftpunktocat-thomas.gif" />
<img id="sk" src="http://octodex.github.com/images/skitchtocat.png" />
<canvas id="canvas"></canvas>
<script>
var image1 = document.getElementById('dp');
var image2 = document.getElementById('sk'); //this is the one we rotate
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");
var DEGREES_TO_ROTATE = 135;
var coordinates = [50, 50];
canvas.width = canvas.height = 400;
ctx.drawImage(image1, 0, 0, 32, 32);
ctx.drawImage(image2, 32, 32, 32, 32);
image2Pixels = ctx.getImageData(32, 32, 32, 32);
canvasImageRotate(ctx, image2Pixels, 32, 32, DEGREES_TO_ROTATE);
</script>
</body>
</html>
function canvasImageRotate(ctx, imagePixels, width, height, degrees) {
var widthHalf = Math.floor(width / 2);
var heightHalf = Math.floor(height / 2);
ctx.save();
ctx.translate(x, y);
ctx.translate(widthHalf, heightHalf);
ctx.rotate((Math.PI / 180) * degrees);
ctx.drawImage(imagePixels, -widthHalf, -heightHalf);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment