旋转两个矩形画布

时间:2014-04-10 03:30:03

标签: javascript html5 canvas

我有一个 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);

1 个答案:

答案 0 :(得分: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