0

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

        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>

请注意,代码可能不正确,因为这是我不久前所做的,我只是想了解如何执行此操作以及是否可能...感谢您的帮助。

4

2 回答 2

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);​
于 2012-06-27T21:52:04.547 回答
0

图像正在异步加载。这意味着整个函数(减去onload图像的处理程序)首先发生。然后在加载图像时,调用它们的处理程序。这发生在第二次传递中。到发生这种情况时,您已经有效地旋转并恢复了画布消除旋转。

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

于 2012-06-28T01:37:49.233 回答