简体   繁体   中英

Rotate two rectangles Canvas

I have a Rectangle with 20x20px and a and another with 5x3px like in the image

矩形的图像

I want to Rotate the entire Rectangle from the center.

I tried this but doesn't work.

//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);

You can ignore the second rotate and just draw the second rectangle offset as if it was non-rotated:

//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

Just note that as the code was and is the rectangle will be rotated from its corner. To adjust for that do this adjustment:

//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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM