[英]Rotate image by 90 degrees on HTML5 Canvas
我无法使用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);
这肯定会帮助你>> HTML5 Canvas旋转图像 :)
使用一些SEPARATE js函数绘制画布:
function drawRotated(degrees){
contex_var.clearRect(0,0,canvas.width,canvas.height);
contex_var.save();
contex_var(canvas.width/2,canvas.height/2);
contex_var.rotate(degrees*Math.PI/180);
contex_var.drawImage(image,-image.width/2,-image.width/2);
contex_var.restore();
}
适合任何buttonclick功能:
$("#clockwise").click(function(){
angleInDegrees+=30;
drawRotated(angleInDegrees);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.