在HTML5画布中,有没有办法以不同的角度旋转图像?

时间:2012-06-26 11:17:40

标签: javascript canvas html5-canvas rotation

目前我想在画布上旋转两个图像,我尝试保存并恢复但是没有工作

        function SetCanvas()
       {
        var canvas = document.getElementById('pic1');

        if(canvas.getContext)
        {
             var ctx = canvas.getContext('2d');
          //    ctx.save();
              ctx.rotate(0.5);
             var image = new Image();
              image.src ='ME.JPG';
              image.onload = function(){

                  ctx.drawImage(image, 90,0,200,100);

              };
        }
            //ctx.restore();
            var canvas2 = document.getElementById("pic2");
            var image2 = new Image();
            image2.src = 'ME2.JPG';
            if(canvas2.getContext)
            {
                    image2.onload = function(){
                            ctx2=canvas2.getContext('2d');
                            ctx2.drawImage(image2, 0,0,200,100); 
                    };
            }


        }

          <ul id="picsCanvas" style="overflow:hidden;white-space:nowrap; list-style-type:none;">
               <li style=" display:inline; float:left" id="first">
                    <canvas ID="pic1" width="300" height="360" ></canvas>
               </li>
                <li id="second" style="margin-top:0px; display:inline; float:left; position:absolute ">
                    <canvas id="pic2" width="300" height="360"  style="position:absolute" ></canvas>
               </li>
            </ul>

请注意,代码可能不正确,因为这是我前一段时间做过的事情,我只是想知道如何做到这一点以及是否有可能...感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

这两个链接提供了一个很好的解释和如何使用HTML5画布旋转的示例

https://developer.mozilla.org/en/Drawing_Graphics_with_Canvas

https://developer.mozilla.org/en/Canvas_tutorial/Basic_animations

旋转时设置不同的角度(请参阅下面的代码示例)。 它的一般要点是:

1) save the context
2) transform to, usually, the center of the image
3) rotate
4) transform back
5) draw image
6) restore

在您的情况下,对于两个图像,您需要在进行第二次旋转调用之前将原点转换为第二个图像。下面是旋转一个图像的简化示例。将其排序,然后进行第二次转换/旋转。

示例:

var canvas = document.getElementById("yourCanvas");
var ctx     = canvas.getContext("2d");
var angle = 0;
window.setInterval(function(){
    angle = angle+1;
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    ctx.save();
    ctx.fillStyle = "#FF0000";

    // first image
    ctx.translate(150,200);
    ctx.rotate( angle*Math.PI/180 );  // rotate 90 degrees
    ctx.translate(-150,-200);

    ctx.fillStyle = "black";  
    ctx.fillRect(100, 150, 100, 100); 
    ctx.fill();

    ctx.restore();
}, 5);​

答案 1 :(得分:0)

图像是异步加载的。这意味着整个函数(减去图像的onload处理程序首先发生。然后当图像被加载时,它们的处理程序被调用。这发生在第二遍。当这发生时,你已经旋转了恢复画布,有效地擦除旋转。

简单的解决方法是在每个图像onload处理程序中旋转和恢复画布。