2011-02-13 45 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