2014-04-10 30 views
0

我有20x20px和另有一个矩形5x3px像图像旋转两个长方形帆布

Image of Rectangles

我想从旋转中心的整个矩形。

我试过这个,但不起作用。

//Rectangle 
ctx.translate(pX,pY); 
ctx.rotate((Math.PI/2*gravity)); 
ctx.fillStyle = "#FF0000"; 
ctx.fillRect(0,0, pHeight, pWidth); 

//blue Rectagle  
ctx.translate(pX+(pWidth-5),pY+(pHeight/2)); 
ctx.fillStyle = "#000FFF"; 
ctx.fillRect(0,0,5,3); 
ctx.translate(-(pX+(pWidth-5)),-(pY+(pHeight/2))); 

ctx.rotate(-(Math.PI/2*gravity)); 
ctx.translate(-pX,-pY); 

回答

0

可以忽略第二转动而只是绘制第二个矩形偏移,如果它是不旋转的:

//Rectangle 
ctx.translate(pX,pY); 
ctx.rotate((Math.PI/2*gravity)); 
ctx.fillStyle = "#FF0000"; 
ctx.fillRect(0,0, pHeight, pWidth); 

//blue Rectagle  
ctx.fillStyle = "#000FFF"; 
ctx.fillRect(pWidth-5, pY+(pHeight/2), 5,3); 

ctx.setTransform(1,0,0,1,0,0); // reset all transforms with identity matrix 

只是注意,由于该代码是和是矩形将从旋转它的角落。要调整为做此调整:

//Rectangle 
ctx.translate(pX,pY); 
ctx.rotate((Math.PI/2*gravity)); 
ctx.fillStyle = "#FF0000"; 
ctx.fillRect(-pHeight*0.5, -pWidth*0.5, pHeight, pWidth); // centered 

//blue Rectagle  
ctx.fillStyle = "#000FFF"; 
ctx.fillRect(pWidth*0.5-5, 0, 5,3); // centered 

ctx.setTransform(1,0,0,1,0,0); // reset all transforms with identity matrix 

Live demo

+0

它的工作原理。但是当我运行动画时,蓝色的矩形渐渐消失。 – Alaeddine

+0

@Alaeddine你可以设置一个小提琴 - 因为“动画”非常微妙,所以更容易理解这个问题。如果你想旋转它们只需要变换动画(平移/旋转),就不需要改变矩形的位置。 – K3N

+0

谢谢我解决了这个问题 – Alaeddine