javascript – 在HTML5 Canvas上将图像旋转90度

我无法使用 HTML5画布旋转图像.我想我的数学错误,并希望得到任何帮助.

在移动设备上,我在150px x 558px画布上捕获用户签名.我试图创建一个558像素×150像素的图像,这只是旋转90度的捕获特征.下面是我目前提出的代码片段.正如你可能猜测的那样,我对数学的掌握并不好.我相信我的程序是正确的,而不是数字.

我想要做的是:
1)将画布的中心设置为中间,偏移图像的高度和宽度
2)将画布旋转90度
3)绘制图像
4)将画布翻译回来.

编辑:这是一个JSFiddle:http://jsfiddle.net/x9FyK/

var $signature = $("#signature");
    var signatureData = $signature.jSignature("getData");

    console.log(signatureData);

    var img= new Image();
    img.onload = function() {
        var rotationCanvas = document.createElement('canvas');
        rotationCanvas.width = img.height;
        rotationCanvas.height = img.width;

        var context = rotationCanvas.getContext("2d");
        context.translate((rotationCanvas.width/2) - (img.width/2), -(rotationCanvas.height/2) - img.height/4);

        context.rotate(Math.PI/2);
        context.drawImage(img,0,0);
        context.translate(-((rotationCanvas.width/2) - (img.width/2)), -(-(rotationCanvas.height/2) - img.height/4));
        var rotatedData = rotationCanvas.toDataURL();

        ...Handling rotated data here

    };
    img.src = signatureData;

如果我能提供更多信息,请告诉我.

在此先感谢您的帮助,

有几种方法可以将已转换(已转换的旋转)画布重置为其原始状态.

Low-Pointer的答案是使用context.save将上下文保存为原始的未转换状态,并使用context.restore在绘制完成后将上下文恢复到其原始状态.

另一种方式是以与执行它们相反的顺序撤消变换.

另请注意,context.translate实际上会将画布原点移动到画布的中心.由于图像是从它们的左上角(而不是它们的中心)绘制的,因此如果您希望图像在画布中居中,则必须将drawImage偏移图像宽度和高度的一半.

这是和例子:http://jsfiddle.net/m1erickson/EQx8V/

// translate to center-canvas 
// the origin [0,0] is now center-canvas

ctx.translate(canvas.width/2,canvas.height/2);

// roate the canvas by +90% (==Math.PI/2)

ctx.rotate(Math.PI/2);

// draw the signature
// since images draw from top-left offset the draw by 1/2 width & height

ctx.drawImage(img,-img.width/2,-img.height/2);

// un-rotate the canvas by -90% (== -Math.PI/2)

ctx.rotate(-Math.PI/2);

// un-translate the canvas back to origin==top-left canvas

ctx.translate(-canvas.width/2,-canvas.height/2);

// testing...just draw a rect top-left

ctx.fillRect(0,0,25,10);