我的目标是制作一个画布,我可以轻松地更改比例并为图像指定不同的旋转度。并将其显示在画布的中心。但是,当我在旋转之前翻译画布时,它并不会使对象居中。
我相当肯定问题在于我对translate和drawImage的计算,但我不确定正确的公式是什么。
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" />
&#13;