Rotate an image around its center in canvas
just change the order of your code, i.e.,
ctx.rotate(...);
ctx.drawImage(...);
See a working example http://jsbin.com/owuyiq/
$(function () {
var canvas = document.getElementById('logobg1');
var ctx = canvas.getContext('2d');
var img = new Image();
var ang = 0; //angle
var fps = 1000 / 25; //number of frames per sec
img.onload = function () { //on image load do the following stuff
canvas.width = this.width << 1; //double the canvas width
canvas.height = this.height << 1; //double the canvas height
var cache = this; //cache the local copy of image element for future reference
setInterval(function () {
ctx.save(); //saves the state of canvas
ctx.clearRect(0, 0, canvas.width, canvas.height); //clear the canvas
ctx.translate(cache.width, cache.height); //let's translate
ctx.rotate(Math.PI / 180 * (ang += 5)); //increment the angle and rotate the image
ctx.drawImage(img, -cache.width / 2, -cache.height / 2, cache.width, cache.height); //draw the image ;)
ctx.restore(); //restore the state of canvas
}, fps);
};
img.src = 'http://i.stack.imgur.com/Z97wf.jpg?s=128'; //img
});
Based on the comments above, but a bit more simple and in vanilla. This one worked for me perfectly. Of course you should use clearRect in order to erase the canvas on each rendering.
var canvas = document.querySelector('#my-canvas');
var ctx = canvas.getContext('2d')
var ang = 0
function rotateAndRenderImg() {
var img = document.querySelector('img')
ctx.save()
var pos = {x: desiredRenderPosX, y: desiredRenderPosY}
ctx.translate(pos.x ,pos.y)
ctx.rotate(Math.PI / 180 * (ang += 5))
ctx.drawImage(img, -img.width / 2, -img.height / 2, img.width, img.height)
ctx.restore()
}