2012-06-26 53 views
0

目前有兩個相同的圖片,我想在畫布上旋轉,我想保存和恢復,但沒有奏效在HTML5畫布中,有沒有辦法以不同角度旋轉圖像?

 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> 

請注意該代碼可能是不正確的,因爲它是我做了而之前,我只想了解如何做到這一點,如果有可能......感謝您的幫助。

回答

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

的圖像被加載異步。這意味着整個函數(減去圖像的onload處理程序首先發生,然後當圖像被加載時,它們的處理程序被調用,這在第二遍時發生,在這種情況發生時,您已經旋轉並恢復了畫布,

簡單的修復方法是旋轉並恢復每個圖像中的畫布onload處理程序