2011-02-13 4 views
-1

어떻게 작동하지 않습니까? 이미지 작업 만 회전합니까? 당신이 context.rotate를 사용할 때사각형을 그려서 회전 시키시겠습니까?

  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

당신은 전체 캔버스를 회전하고, 피벗 포인트 좌표에 기본값으로되어 있기 때문에 (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

+0

여기 있습니다 : http://jsfiddle.net/FWvYg/ – user824294

+0

고마워! @ user824294 – RooWM

관련 문제