首页 文章

在HTML5 Canvas上将图像旋转90度

提问于
浏览
4

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

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

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

EDIT: Here's a 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;

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

在此先感谢您的帮助,

2 回答

  • 4

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

    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);
    

    enter image description here

  • 11

    这肯定会帮助你>> HTML5 Canvas Rotate Image :)

    使用一些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);
    });
    

相关问题