Javascript 旋转两个矩形画布
在图像中,我有一个带20x20px的矩形和一个带5x3px的矩形 我想从中心旋转整个矩形 我试过了,但没用Javascript 旋转两个矩形画布,javascript,html,canvas,Javascript,Html,Canvas,在图像中,我有一个带20x20px的矩形和一个带5x3px的矩形 我想从中心旋转整个矩形 我试过了,但没用 //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))
//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);
您可以忽略第二个旋转,只需绘制第二个矩形偏移,就像它未旋转一样:
//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
它可以工作。但是当我运行动画时,蓝色的矩形正在消失。@Alaeddine你能摆弄一下小提琴吗?这样更容易理解这个问题,因为“动画”非常微妙。如果要旋转它们,只需设置变换动画(平移/旋转),无需更改矩形的位置。谢谢,我已经解决了这个问题