繁体   English   中英

如何将包含图像的画布旋转90、180、270度?

[英]How can I rotate a Canvas containing an Image by 90, 180, 270 Degrees?

我有一个包含图像的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,因为我需要画布进行进一步处理。

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

最好在画布上旋转图像。

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

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

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

  • 0度== 0弧度
  • 90度==数学PI / 2弧度
  • 180度== Math.PI弧度
  • 270度==数学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/stackoverflow/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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM