【问题标题】:How can I rotate a Canvas containing an Image by 90, 180, 270 Degrees?如何将包含图像的画布旋转 90、180、270 度?
【发布时间】:2014-07-23 04:16:30
【问题描述】:

我有一个包含图像的 HTML5 画布。现在我想将这个画布旋转 x 度。

我所做的是:

function getRadianAngle(degreeValue) {
    return degreeValue * Math.PI / 180;
} 

var rotateCanvas = function(canvas, image, degrees) {
  var context = canvas.getContext('2d');
  context.rotate(getRadianAngle(degrees));
  context.drawImage(image, 0, 0);
  return canvas;            
}

var image = new Image();
image.onload = function() {
   var canvas = document.createElement("canvas");
   var context = canvas.getContext('2d');
   var cw = canvas.width = image.width;
   var ch = canvas.height = image.height;
   context.drawImage(image, 0, 0, image.width, image.height);

   rotateCanvas(canvas, image, 180);
}
image.src = // some image url;

此代码无法正常工作。

如何定义旋转函数来旋转画布?

编辑:我不想使用 css,因为我需要画布进行进一步处理。

【问题讨论】:

    标签: javascript html canvas rotation


    【解决方案1】:

    可以使用 CSS 来旋转画布,但如果画布是矩形而不是正方形,则可能会弄乱您的页面设计。

    在画布上旋转图像可能会更好。

    • 清除现有画布。
    • 平移到旋转点--x=image.x+image.width/2,y=image.y+image.height/2。
    • 旋转。
    • drawImage(image,-image.width/2,-image.height/2

    示例代码和演示:http://jsfiddle.net/m1erickson/8uRaL/

    顺便说一句,您所需角度的弧度是:

    • 0 度 == 0 弧度
    • 90 度 == Math.PI/2 弧度
    • 180 度 == Math.PI 弧度
    • 270 度 == Math.PI*3/2 弧度

    示例代码:

    <!doctype html>
    <html>
    <head>
    <link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
    <style>
        body{ background-color: ivory; }
        canvas{border:1px solid red;}
    </style>
    <script>
    $(function(){
    
        var canvas=document.getElementById("canvas");
        var ctx=canvas.getContext("2d");
    
        var radians=0;
    
        var img=new Image();
        img.onload=start;
        img.src="https://dl.dropboxusercontent.com/u/139992952/*/cat.png";
        function start(){
            animate();
        }
    
    
        function animate(){
            requestAnimationFrame(animate);
            ctx.clearRect(0,0,canvas.width,canvas.height);
            ctx.save();
            ctx.translate(canvas.width/2,canvas.height/2);
            ctx.rotate(radians);
            ctx.drawImage(img,-img.width/2,-img.height/2);
            ctx.restore();
            radians+=Math.PI/180;
        }
    
    
    }); // end $(function(){});
    </script>
    </head>
    <body>
        <canvas id="canvas" width=300 height=300></canvas>
    </body>
    </html>
    

    【讨论】:

    • 我不想使用 css,因为我需要画布进行进一步处理。
    • 当然...请参阅我的答案的补充。干杯!
    最近更新 更多