My goal is to make a canvas where I can easily change the scale and specify different degrees of rotation for an image. And also display it in the center of the canvas. However when I translate the canvas before I do that rotation, it doesn't center the object.
I'm fairly positive the problem lies in my calculation for the translate and drawImage but I'm not sure what the proper formula would be.
var canvas = document.getElementById('myCanvas');
var image = new Image();
var dist;
var imgScale = .5;
var imgH, imgW;
var cxt;
image.src = 'http://t2.gstatic.com/images?q=tbn:ANd9GcQQveW9AJCxOC8Phnq3vptJIxPFHlxNw63q4pudc66dM4O96vtm';
image.onload = function() {
imgH = image.height * imgScale;
imgW = image.width * imgScale;
dist = Math.ceil(Math.pow((Math.pow(imgW, 2) + Math.pow(imgW, 2)), .5));
canvas.width = dist;
canvas.height = dist;
cxt = canvas.getContext('2d');
cxt.save();
cxt.translate(canvas.width / 2 - imgW / 2, canvas.height / 2 - imgH / 2);
cxt.drawImage(image, 0, 0, imgW, imgH);
cxt.restore();
//
setTimeout(function() {
cxt.save();
//Suspect line
cxt.translate(canvas.width / 2 - imgW / 2, canvas.height / 2 - imgH / 2);
cxt.rotate(45 * Math.PI / 180);
//Suspect line
cxt.drawImage(image, 0, 0, imgW, imgH);
cxt.restore();
}, 1000);
};
<canvas id="myCanvas" style="border: 1px solid black" />