Last active
December 18, 2015 10:59
-
-
Save jmjpro/5772557 to your computer and use it in GitHub Desktop.
rotate an image on an HTML5 canvas
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
<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> |
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 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