2011-02-13 89 views
-1

這是怎麼回事?是否只能旋轉圖像?畫正方形並旋轉它?

  context.moveTo(60,60); 
      context.lineTo(200,60); 
      context.lineTo(200,200); 
      context.lineTo(60,200); 
      context.lineTo(60,60); 


      context.stroke(); 
      context.rotate(45 * Math.PI/180); 
      context.restore(); 

回答

3

你轉動整個畫布當您使用context.rotate,由於樞軸點是在默認座標(0,0),你方有時會被吸引出界。

通過將樞軸點移動到正方形的中間,然後可以成功旋轉它。

注意:確保在繪製正方形之前旋轉畫布。

// pivot point coordinates = the center of the square 
var cx = 130; // (60+200)/2 
var cy = 130; // (60+200)/2 

// Note that the x and y values of the square 
// are relative to the pivot point. 
var x = -70; // cx + x = 130 - 70 = 60 
var y = -70; // cy + y = 130 - 70 = 60 
var w = 140; // (cx + x) + w = 60 + w = 200 
var h = 140; // (cy + y) + h = 60 + h = 200 
var deg = 45; 

context.save(); 

context.translate(cx, cy); 
context.rotate(deg * Math.PI/180); 

context.fillRect(x, y, w, h); 

context.restore(); 


說明:

  • context.save();保存座標系統的當前狀態。

  • context.translate(cx, cy);移動樞軸點。

  • context.rotate(deg * Math.PI/180);旋轉廣場deg度(請注意參數是弧度,不度)

  • context.fillRect(x, y, w, h);繪製方形

  • context.restore();恢復座標系統的最後狀態。

這是JS Fiddle example

這是另一個JS Fiddle example that features a HTML5 slider

+0

有沒有辦法讓這個旋轉而不用滑塊,而是通過觸摸對象本身? – RooWM 2012-12-13 16:22:36