如何在相反的方向上[在同一个画布上]旋转两个图像?

时间:2013-03-26 18:39:11

标签: javascript

我无法使用canvas state()和restore()函数以相反的方向旋转两个图像。非常感谢任何解决方案,谢谢!

这是我的代码:

program.ctxT.globalCompositeOperation = 'destination-over';
program.ctxT.save();

program.ctxT.clearRect(x - 1, 0 - 1, 72, 62);
program.ctxT.translate(x + 35, 0 + 25);
program.ctxT.rotate(Math.PI / 135);
program.ctxT.translate(-(x + 35), -(0 + 25));
program.ctxT.drawImage(program.imgBody, x, 0);
program.ctxT.restore();

program.ctxT.globalCompositeOperation = 'destination-over';
program.ctxT.save();

program.ctxT.translate(x + 35, 0 + 25);
program.ctxT.rotate(Math.PI / -135);
program.ctxT.translate(-(x + 35), -(0 + 25));
program.ctxT.drawImage(program.imgHead, x, 0);
program.ctxT.restore();

1 个答案:

答案 0 :(得分:0)

对于这种误解感到抱歉,我还是刚刚在Stack Exchange上发帖的新手。我的问题还没有完全理解save()和restore()是如何工作的(当然),但这是我最好的解释;执行稍后要应用的转换/状态更改并保存()那些,然后将自己与先前的状态更改分开,并执行一组不同的状态更改以应用于下一个图像/形状,继续执行此操作直到您到达你想要独立变换的最后一项(作为一个注释,使用最后一项,你不必保存,只需绘制你想要的项目)。现在所有的转换都已完成并保存,并且您已经绘制了第一个项目,然后使用restore()然后绘制您想要绘制的下一个项目,继续为您想要绘制的所有项目。需要注意的一件重要事情是globalCompositeOperation属性,搜索它,因为这决定了图像的堆叠方式。希望这个解释是合理的,我为不早点这样做而道歉。

function update() {
   //Merely clearing the canvas in the area our image was previously in.
   program.ctxT.clearRect(x - 35, 0 - 18, 108, 81);

   //Rotate canvas and save this state, this will be applied to the body or underlying element.
   rotCentre(35, 25, Math.PI / -135);
   program.ctxT.save();

   //This keeps track of the body rotation.
   rot++;

   //Applies the same rotation as earlier to move the head with the body.
   program(35, 25, Math.PI / -135);

   /* Although the head moves with the body, it should not changes its facing, so compensation. 
   The title says two images moving in opposite directions, but this only kind of does that, 
   if you do want them to be visually moving in opposite directions, just multiply the rot by
   a number greater than one.*/
   program(8, 8, rot * Math.PI / 135);

   //Draw the overlaying image (head).
   program.ctxT.drawImage(program.imgHead, x, 0);

   //Moving onto the lower layer, restore the transformations we are using for it and draw.
   program.ctxT.restore();
   program.ctxT.drawImage(program.imgBody, x - 35, -17.3);
}   

function rotCentre(centreX, centreY, angle) {
   //This allows the head to be overlayed.
   program.ctxT.globalCompositeOperation = 'destination-over';

   //First translate the context so that it will rotate around the image's centre.
   program.ctxT.translate(x + centreX, 0 + centreY);
   program.ctxT.rotate(angle);

   //Remember to put the context back to its original position!
   program.ctxT.translate(-(x + centreX), -(0 + centreY));
}